commit 692ee4fa321452aed7434490e697e5ec7e53b7ae Author: Oleg Proskurin Date: Sat Sep 13 23:02:51 2025 +0700 Init project diff --git a/.claude/commands/generate.md b/.claude/commands/generate.md new file mode 100644 index 0000000..97106df --- /dev/null +++ b/.claude/commands/generate.md @@ -0,0 +1,70 @@ +--- +description: Generate a professional image using Gemini Flash via Nano Banana MCP from free-form description +argument-hint: +allowed-tools: [Read, Write, Glob, Grep, Bash, mcp__nano-banana-mcp__generate_image, mcp__nano-banana-mcp__get_configuration_status] +--- + +Generate a professional image based on the user description: "$ARGUMENTS" + +Follow these steps: + +1. **Configuration Check**: First verify that Gemini API is properly configured using `mcp__nano-banana-mcp__get_configuration_status` + +2. **Context Discovery**: Automatically search for and gather relevant context from the project files: + - Search for any mentioned characters in `/heroes/` directory + - Look for locations in `/locations/` or `/cities/` directories + - Find world information in `/worlds/` directory + - Identify items in `/items/` directory + - Check for creatures in `/creatures/` directory + - Find applicable settings in `/settings/` directory + +3. **Entity Analysis**: Parse the description to identify: + - Characters mentioned (explicit or implied) + - Locations referenced + - Items involved + - Creatures present + - Scene context and actions + - Appropriate style settings to apply + +4. **Prompt Generation**: Create a professional prompt following the guidelines in `@docs/prompting-guide.md`: + - Use narrative descriptions instead of keyword lists + - Apply appropriate template from the prompting guide based on content type + - Include world-specific style elements + - Reference character unique identifying features + - Integrate linked items and relationships naturally + - Specify lighting and atmosphere + - Include technical quality descriptors + - Maintain visual continuity with established universe + +5. **Settings Integration**: Automatically apply appropriate settings based on context: + - Character clothing based on status, world, and scenario + - Transportation methods suitable for world and character + - Environmental styles matching location and world + - Weapon styles appropriate for character and scenario + - Magical effects suitable for character abilities + +6. **Image Generation**: Use `mcp__nano-banana-mcp__generate_image` with the professionally crafted prompt + +7. **File Management**: Upon successful generation: + - Save image to appropriate directory based on content: + - Character portraits → `/heroes/{character-name}/photos/` + - Location shots → `/locations/{location-name}/images/` or `/cities/{city-name}/images/` + - Item visualizations → `/items/{item-name}/images/` + - Creature images → `/creatures/{creature-name}/images/` + - Scene compositions → `/scenes/{scene-name}/images/` + - Archive the successful prompt in corresponding `/prompts/` directory + - Update cross-references if new relationships are established + +8. **Documentation**: Create a markdown file in `/prepared_prompts/` directory documenting: + - The final prompt used + - Applied settings and context + - Generated image path + - Validation results and suggestions + - Entity relationships discovered + +**Important**: +- The prompt must be in English regardless of input language +- Follow exact templates and best practices from `docs/prompting-guide.md` +- Respect the project framework defined in `CLAUDE.md` +- Use `mcp__nano-banana-mcp__generate_image` tool for actual image generation +- Ensure proper file organization according to project structure \ No newline at end of file diff --git a/.claude/commands/prompt.md b/.claude/commands/prompt.md new file mode 100644 index 0000000..b0551f5 --- /dev/null +++ b/.claude/commands/prompt.md @@ -0,0 +1,60 @@ +--- +description: Generate a professional Gemini Flash Image prompt from free-form description +argument-hint: +allowed-tools: [Read, Write, Glob, Grep, Bash] +--- + +Create a professional image generation prompt based on the user description: "$ARGUMENTS" + +Follow these steps: + +1. **Context Discovery**: Automatically search for and gather relevant context from the project files: + - Search for any mentioned characters in `/heroes/` directory + - Look for locations in `/locations/` or `/cities/` directories + - Find world information in `/worlds/` directory + - Identify items in `/items/` directory + - Check for creatures in `/creatures/` directory + - Find applicable settings in `/settings/` directory + +2. **Entity Analysis**: Parse the description to identify: + - Characters mentioned (explicit or implied) + - Locations referenced + - Items involved + - Creatures present + - Scene context and actions + - Appropriate style settings to apply + +3. **Prompt Generation**: Create a professional prompt following the guidelines in `@docs/prompting-guide.md`: + - Use narrative descriptions instead of keyword lists + - Apply appropriate template from the prompting guide based on content type + - Include world-specific style elements + - Reference character unique identifying features + - Integrate linked items and relationships naturally + - Specify lighting and atmosphere + - Include technical quality descriptors + - Maintain visual continuity with established universe + +4. **Settings Integration**: Automatically apply appropriate settings based on context: + - Character clothing based on status, world, and scenario + - Transportation methods suitable for world and character + - Environmental styles matching location and world + - Weapon styles appropriate for character and scenario + - Magical effects suitable for character abilities + +5. **Reference Images**: If the prompt requires reference images, include their file paths in markdown format. + +6. **Validation**: Check the generated prompt against best practices: + - Ensure narrative structure (not keyword lists) + - Include lighting and atmosphere descriptions + - Specify technical quality requirements + - Maintain consistency with established character/location features + - Follow appropriate template from prompting guide + +7. **Output**: Save the final prompt as a markdown file in `/prepared_prompts/` directory with: + - Timestamp and description in filename + - Complete prompt ready for Gemini 2.5 Flash Image + - Applied settings documentation + - Reference image paths if needed + - Validation results and suggestions + +**Important**: The output must be in English regardless of input language. Follow the exact templates and best practices from `docs/prompting-guide.md` and respect the project framework defined in `CLAUDE.md`. \ No newline at end of file diff --git a/.claude/commands/update.md b/.claude/commands/update.md new file mode 100644 index 0000000..3d83fa1 --- /dev/null +++ b/.claude/commands/update.md @@ -0,0 +1,87 @@ +--- +description: Edit/update an existing image using Gemini Flash via Nano Banana MCP with professional prompting +argument-hint: +allowed-tools: [Read, Write, Glob, Grep, Bash, mcp__nano-banana-mcp__edit_image, mcp__nano-banana-mcp__continue_editing, mcp__nano-banana-mcp__get_last_image_info, mcp__nano-banana-mcp__get_configuration_status] +--- + +Edit/update an existing image based on the provided image path and edit description. + +**Usage**: `/update ` +**Example**: `/update /heroes/camelot/photos/portrait.jpg add a mystical staff in his hand` + +Follow these steps: + +1. **Configuration Check**: First verify that Gemini API is properly configured using `mcp__nano-banana-mcp__get_configuration_status` + +2. **Image Path Validation**: + - Parse the first argument as the image path + - Verify the image file exists and is accessible + - Extract the remaining arguments as the edit description + - If no image path provided, check if there's a recent image using `mcp__nano-banana-mcp__get_last_image_info` + +3. **Context Discovery**: Based on the image location and edit description, gather relevant context: + - If image is in `/heroes/` directory, load character description + - If in `/locations/` or `/cities/`, load location context + - If in `/items/`, load item specifications + - If in `/creatures/`, load creature details + - Search for applicable settings in `/settings/` directory + - Load world information from `/worlds/` directory if applicable + +4. **Entity Analysis**: Parse the edit description to identify: + - Changes requested (add, remove, modify elements) + - New elements to be introduced + - Style preferences or requirements + - Lighting or mood adjustments + - Technical specifications needed + +5. **Edit Prompt Generation**: Create a professional edit prompt following `@docs/prompting-guide.md` editing templates: + - **Adding/Removing Elements**: "Using the provided image of [subject], please [add/remove/modify] [element] to/from the scene. Ensure the change is [integration description]." + - **Inpainting**: "Using the provided image, change only the [specific element] to [new element]. Keep everything else exactly the same, preserving the original style, lighting, and composition." + - **Style Transfer**: "Transform the provided image into [artistic style]. Preserve the original composition but render it with [stylistic elements]." + - **Detail Preservation**: "Using the provided image, [edit request]. Ensure that [critical details] remain completely unchanged. The modification should [integration requirements]." + +6. **Settings Integration**: Apply appropriate settings for consistency: + - Maintain character clothing styles if character is present + - Preserve world-specific aesthetic elements + - Apply environmental settings for background consistency + - Include weapon/item styling if applicable + - Maintain magical effects consistency + +7. **Reference Image Handling**: Determine editing approach: + - If editing a specific image file: use `mcp__nano-banana-mcp__edit_image` with the image path + - If continuing work on the last generated image: use `mcp__nano-banana-mcp__continue_editing` + - Include additional reference images if needed for style transfer or element addition + +8. **Image Generation**: Execute the edit using the appropriate MCP tool: + - `mcp__nano-banana-mcp__edit_image` for specific file edits + - `mcp__nano-banana-mcp__continue_editing` for iterative improvements + +9. **File Management**: Upon successful generation: + - Save updated image in the same directory structure + - Create versioned filename if preserving original + - Archive the successful edit prompt in corresponding `/prompts/` directory + - Update any cross-references if relationships changed + +10. **Documentation**: Create a markdown file in `/prepared_prompts/` directory documenting: + - Original image path and edit description + - Final edit prompt used + - Applied settings and context + - Generated image path + - Edit type and template used + - Validation results + +**Edit Types Supported**: +- **Element Addition**: Adding objects, characters, effects to existing image +- **Element Removal**: Removing unwanted elements while maintaining scene integrity +- **Modification**: Changing colors, expressions, poses, clothing, etc. +- **Style Transfer**: Converting image to different artistic style +- **Inpainting**: Replacing specific parts while preserving the rest +- **Composition Changes**: Adjusting framing, perspective, lighting + +**Important**: +- The edit prompt must be in English regardless of input language +- Follow exact editing templates from `docs/prompting-guide.md` +- Preserve critical details mentioned in project files +- Maintain consistency with established character/location features +- Use appropriate MCP tool based on editing scenario +- Ensure proper file versioning to preserve original if needed \ No newline at end of file diff --git a/.env b/.env new file mode 100644 index 0000000..6c1f844 --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +GEMINI_API_KEY=AIzaSyAWAy39gqmnrYA0kUC3Vh8uadu-WlqJuO4 + diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000..7642057 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,14 @@ +{ + "mcpServers": { + "nano-banana-mcp": { + "type": "stdio", + "command": "npx", + "args": [ + "nano-banana-mcp" + ], + "env": { + "GEMINI_API_KEY": "AIzaSyAWAy39gqmnrYA0kUC3Vh8uadu-WlqJuO4" + } + } + } +} \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..7772c3a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,317 @@ +# Fantasy Universe Visual Generation Framework + +## Project Overview + +This repository contains a comprehensive fantasy universe with parallel worlds, locations, and characters. The system is designed to generate consistent visual representations using Gemini Flash Image (Nano Banana) through Claude Code and the Nano-Banana-MCP integration. + +## Project Structure + +``` +/ +├── CLAUDE.md # This file +├── PROJECT_STANDARDS.md # Quality and style requirements +├── cities/ +│ └── {city-name}/ +│ ├── description.md # City overview and lore +│ ├── images/ # Generated city views +│ ├── prompts/ # Successful prompts archive +│ └── locations/ +│ └── {location-name}.md +├── locations/ +│ └── {location-name}/ +│ ├── description.md # Location details and lore +│ ├── images/ # Generated location images +│ └── prompts/ # Successful prompts archive +├── heroes/ +│ └── {hero-name}/ +│ ├── description.md # Character details and traits +│ ├── photos/ # Character portraits and scenes +│ └── prompts/ # Character-specific prompts +├── worlds/ +│ └── {world-name}/ +│ ├── description.md # World rules and aesthetics +│ └── style-guide.md # Visual style requirements +├── items/ +│ └── {item-name}/ +│ ├── description.md # Item properties and lore +│ ├── images/ # Item visualizations +│ └── prompts/ # Item-specific prompts +├── creatures/ +│ └── {creature-name}/ +│ ├── description.md # Creature details and abilities +│ ├── images/ # Creature visualizations +│ └── prompts/ # Creature-specific prompts +├── settings/ +│ ├── clothing/ +│ │ └── {style-name}/ +│ │ ├── description.md # Style specifications and usage +│ │ ├── images/ # Reference style images +│ │ └── prompts/ # Style-specific prompts +│ ├── transportation/ +│ │ └── {transport-type}/ +│ │ ├── description.md # Transportation style details +│ │ ├── images/ # Reference images +│ │ └── prompts/ # Transportation prompts +│ ├── weapons/ # Weapon styles and designs +│ ├── environments/ # Environmental style references +│ ├── architecture-styles/ # Architectural design patterns +│ └── magical-effects/ # Magical visual effect styles +└── scenes/ + └── {scene-name}/ + ├── description.md # Scene context and story + └── images/ # Generated scene images +``` + +## Entity Relationship System + +### Cross-Reference Links +Each entity can reference other entities through standardized linking syntax in their description.md files: + +- **Characters**: `[Character:name]` - Links to heroes/{name}/description.md +- **Locations**: `[Location:name]` - Links to locations/{name}/description.md or cities/{city}/locations/{name}.md +- **Worlds**: `[World:name]` - Links to worlds/{name}/description.md +- **Items**: `[Item:name]` - Links to items/{name}/description.md +- **Creatures**: `[Creature:name]` - Links to creatures/{name}/description.md +- **Cities**: `[City:name]` - Links to cities/{name}/description.md +- **Settings**: `[Setting:category/name]` - Links to settings/{category}/{name}/description.md + +### Relationship Types +Define relationships between entities using these markers: + +- **Ownership**: `[Item:sword-of-power] (owned by this character)` +- **Combat History**: `[Creature:ice-dragon] (defeated by this character)` +- **Location Associations**: `[Location:library] (frequent visitor)` +- **World Origin**: `[World:winter-world] (native to this world)` +- **Character Relationships**: `[Character:camelot] (father of this character)` +- **Item Interactions**: `[Item:mystical-staff] (can be wielded by this character)` +- **Style Preferences**: `[Setting:clothing/ancient-mage-robes] (typical attire for this character)` + +## Settings System - Style and Visual References + +### Purpose +The `settings/` directory contains reusable visual style references that can be applied across multiple characters, worlds, and scenarios. These are **thematic style guides** rather than specific entities. + +### Categories + +#### Clothing Settings +- **ancient-mage-robes**: Traditional high-status magical practitioner attire +- **modern-tactical-gear**: Contemporary military/security equipment +- **medieval-noble-attire**: Royal and aristocratic clothing styles +- **casual-modern-wear**: Contemporary everyday clothing + +#### Transportation Settings +- **magical-mounts**: Fantasy creature transportation (dragons, unicorns, etc.) +- **modern-vehicles**: Contemporary cars, motorcycles, aircraft +- **medieval-horses**: Traditional horseback transportation +- **futuristic-transport**: Advanced sci-fi transportation methods + +#### Weapon Settings +- **medieval-weapons**: Swords, shields, crossbows, traditional arms +- **modern-firearms**: Contemporary weapons and tactical equipment +- **magical-weapons**: Enchanted and mystical weapons +- **futuristic-weapons**: Advanced technology armaments + +#### Environment Settings +- **magical-forests**: Enchanted woodland environments +- **urban-landscapes**: Modern city environments +- **ancient-ruins**: Historical and archaeological sites +- **winter-landscapes**: Cold weather and snow environments + +#### Architecture Settings +- **medieval-castles**: Traditional fortress and castle designs +- **modern-buildings**: Contemporary architectural styles +- **magical-towers**: Fantasy magical structure designs +- **ancient-temples**: Religious and ceremonial architecture + +#### Magical Effects Settings +- **elemental-magic**: Fire, water, earth, air magical visualizations +- **healing-magic**: Positive magical effect visualizations +- **dark-magic**: Shadow and necromantic magical effects +- **protective-magic**: Barrier and shielding magical effects + +### Settings Integration in Prompts + +#### Automatic Style Application +When generating images, Claude Code should: + +1. **Identify applicable settings** based on character, world, and scenario context +2. **Load relevant style descriptions** from settings files +3. **Integrate style elements** into the generated prompt +4. **Maintain consistency** with established character and world aesthetics + +#### Example Style Integration +``` +Generate [Character:camelot] riding to [Location:guardian-library] + +Auto-loaded styles: +- [Setting:clothing/ancient-mage-robes] for Camelot's attire +- [Setting:transportation/magical-mounts] for his transportation +- [World:camelot-world] style guide for overall aesthetic +``` + +### Style Prompt Template +``` +[Base scene description] + [Character with Setting:clothing/style applied] + [Setting:transportation/method if applicable] + [World style context] + [Setting:environment/type for background] + [Technical specifications] +``` + +## Core Directives for Claude Code + +### 1. Context Discovery and Assembly + +When receiving image generation requests: + +1. **Parse the request** to identify: + - Characters mentioned + - Locations referenced + - Items involved + - Creatures present + - Scene context + - Specific actions or poses + +2. **Automatically gather context** by reading relevant files: + - Character descriptions from `/heroes/{character-name}/description.md` + - Location details from `/locations/{location-name}/description.md` or `/cities/{city-name}/locations/{location-name}.md` + - World style guides from `/worlds/{world-name}/description.md` and `/worlds/{world-name}/style-guide.md` + - Item specifications from `/items/{item-name}/description.md` + - Creature details from `/creatures/{creature-name}/description.md` + - **Style settings** from `/settings/{category}/{style-name}/description.md` + - Reference images from appropriate directories + +3. **Identify applicable settings** automatically: + - Character clothing based on world, status, and scenario + - Transportation methods appropriate to world and character + - Environmental styles matching the location and world + - Weapon styles suitable for character and scenario + - Magical effects appropriate to character abilities + +4. **Follow cross-references** by parsing linked entities: + - When reading a character file, automatically load linked items, locations, and preferred settings + - Resolve creature combat histories for context + - Load world-specific style requirements for characters from different realms + - Apply appropriate setting styles based on character preferences and world context + +5. **Synthesize information** into a comprehensive understanding before prompt creation + +### 2. Prompt Generation Framework + +1. Learn prompting documentation in `docs/prompting-guide.md` with comprehensive guid with best practices of prompting using Gemini 2.5 Flash Image model. +2. Select the best matching case and create a prompt following templates in `docs/prompting-guide.md`, respect best practices described in this document, and adopt them to the actual user request +3. Prepare the professional prompt in English respecting all details and requirements passed by users and this project framework, aligned with documentation, selected template, and best practices + +#### Settings Integration Protocol +- **Automatic Style Detection**: Identify appropriate settings based on character, world, and scenario +- **Style Consistency**: Ensure settings align with established character and world aesthetics +- **Hierarchical Application**: World styles > Character preferences > Scenario requirements +- **Style Combination**: Blend multiple settings when appropriate (clothing + transportation + environment) + +#### Character Consistency Protocol +- **Always reference unique identifying features** from character descriptions +- **Apply appropriate clothing settings** based on character status, world, and scenario +- **Include owned/wielded items** from character links +- **Maintain physical characteristics** across all generations +- **Use specific descriptors** rather than generic terms +- **Reference previous successful images** when available +- **Consider character relationships** for group scenes + +#### Location Consistency Protocol +- **Establish architectural style** from world guidelines and architecture settings +- **Apply appropriate environmental settings** for location type +- **Include signature elements** that make locations recognizable +- **Maintain geographic and environmental logic** +- **Reference existing location images** for consistency +- **Consider location-specific creatures or items** + +#### Item Integration Protocol +- **Reference visual descriptions** from item files +- **Apply appropriate weapon/item settings** for visual consistency +- **Maintain consistent appearance** across scenes +- **Consider item-character compatibility** from relationship links +- **Include magical/special effects** if specified using magical-effects settings + +#### Creature Integration Protocol +- **Use detailed creature descriptions** for accurate representation +- **Consider creature-character relationships** (combat history, alliances) +- **Include creature abilities** in visual representation using appropriate effect settings +- **Maintain creature consistency** across different scenes + +### 3. Settings Usage Examples + +#### Clothing Application +``` +"Generate Camelot in his study" +→ Auto-applies [Setting:clothing/ancient-mage-robes] based on character status +→ Result: Camelot wearing elaborate blue mage robes with golden runic embroidery +``` + +#### Transportation Integration +``` +"Show Eliot traveling to the Guardian Library" +→ Auto-applies [Setting:transportation/magical-mounts] for fantasy world travel +→ Result: Eliot riding a magical steed appropriate to his mage status +``` + +#### Environmental Styling +``` +"Create a scene in the winter world" +→ Auto-applies [Setting:environments/winter-landscapes] for background +→ Result: Appropriate snow, ice, and cold weather environmental details +``` + +### 4. Critical Prompting Guidelines + +#### ALWAYS DO: +- **Use narrative descriptions** instead of keyword lists +- **Include world-specific style elements** in every prompt +- **Apply appropriate settings automatically** based on context +- **Reference character's unique identifying features** consistently +- **Integrate linked items and relationships** naturally +- **Specify lighting and atmosphere** appropriate to the scene +- **Include technical quality descriptors** for professional results +- **Maintain established visual continuity** across the universe +- **Follow cross-reference links** to gather complete context +- **Apply style settings consistently** across related generations + +#### NEVER DO: +- Use disconnected keyword lists +- Ignore established character features +- Generate without consulting existing context files +- Create prompts without world style consistency +- Skip the iterative refinement process +- Forget to specify aspect ratios +- Ignore entity relationships and cross-references +- Apply inappropriate settings that conflict with character or world aesthetics + +### 5. File Management Protocol + +**Upon Image Approval:** +1. **Save image** to appropriate directory: + - Character portraits → `/heroes/{character-name}/photos/` + - Location shots → `/locations/{location-name}/images/` or `/cities/{city-name}/images/` + - Item visualizations → `/items/{item-name}/images/` + - Creature images → `/creatures/{creature-name}/images/` + - Style references → `/settings/{category}/{style-name}/images/` + - Scene compositions → `/scenes/{scene-name}/images/` + +2. **Archive successful prompt** in corresponding `/prompts/` directory with descriptive filename + +3. **Update cross-references** if new relationships are established in the scene + +4. **Create scene description** if the image represents a specific story moment + +5. **Document entity interactions** for future consistency + +6. **Archive style applications** in appropriate settings `/prompts/` directories for reuse + +### 6. Context Integration Commands + +Use these patterns for efficient context gathering: + +- `"Generate {character} in {location}"` → Auto-gather character, location, appropriate settings, and linked entity files +- `"Show {character} wielding {item}"` → Gather character and item descriptions, check compatibility, apply weapon settings +- `"Create {character} fighting {creature}"` → Load combat context from character's creature links, apply appropriate combat settings +- `"Show {location} with {creature} present"` → Gather location and creature contexts, apply environmental settings +- `"Generate scene with {character1} and {character2}"` → Load both characters and their relationship context, apply group scene settings +- `"Style {character} in {setting:category/name}"` → Apply specific style override to character +- `"Show {character} in {world} style"` → Apply world-specific styling to character appearance + +This framework ensures consistent, high-quality visual generation that maintains narrative coherence, character/location integrity, proper entity relationships, and appropriate style application across the entire fantasy universe project. \ No newline at end of file diff --git a/ENTITIES_CHECKLIST.md b/ENTITIES_CHECKLIST.md new file mode 100644 index 0000000..67f3186 --- /dev/null +++ b/ENTITIES_CHECKLIST.md @@ -0,0 +1,133 @@ +# Entities Creation Checklist + +## Remaining Heroes to Create + +### Completed Heroes +- [x] Dan (13 yo boy) +- [x] Nick (14 yo boy) +- [x] Camelot (54 yo, Chief Mage) +- [x] Eliot (18 yo, mage, son of Camelot) + +### Heroes to Create +- [ ] Tim (15 yo boy) +- [ ] Edd (18 yo yuan guy, quantum physics student, son of Konstantin) +- [ ] Konstantin (54 yo, Chief physicist of international quantum physics institute) +- [ ] Bart (18 yo, mage, friend of Eliot) +- [ ] Ender (alter ego of Edd, 18 yo, winter mage-assassin) +- [ ] Nataly (44 yo, Vanechka's mom, chemist scientist, works in Gronin lab) +- [ ] Nissa (14 yo girl) +- [ ] Library Guardian (elf-gnome, 1000 years old) +- [ ] Portal Guardian (elf-gnome, 1000 years old) +- [ ] Guardian-Protector (elf-gnome, 1000 years old) +- [ ] Mara (mage from Camelot world, 24 yo girl) +- [ ] George (engineer-builder from modern world, 25 yo) + +## Items to Create + +- [ ] Dusty Sword (from abandoned building) +- [ ] Dusty Armor (from abandoned building) +- [ ] Archmage Staff +- [ ] Apprentice Mage Staff +- [ ] Mystical Staff (straight, black, polished, no decorations, maximum power) +- [ ] Camelot Staff (high mage staff with green crystal) +- [ ] Owl Figurine (small glass figure of owl, blue colored glass) +- [ ] Gecko Figurine (small glass figure of gecko, blue colored glass) +- [ ] Cat Figurine (small glass figure of jumping cat, blue colored glass) + +## Creatures to Create + +- [ ] Skeleton (aggressive creature controlled externally) +- [ ] Skeleton Warrior (skeleton with helmet and sword) +- [ ] Zombie (green and stinking aggressive creature) +- [ ] Skeleton Spider (huge 10-meter creature, extremely dangerous) +- [ ] Flying Cat (mad aggressive cat with bat wings, metal claws, burning eyes) +- [ ] Ice Birds (huge pterodactyl-like birds from ice magical substance) +- [ ] Snow Giants (huge creatures made of rough snow lumps) +- [ ] Ice Dragon (dangerous dragon from ice magical substance) +- [ ] Snow Dragon (creature created and controlled by George) +- [ ] Snow Birds (large eagle-like birds made of snow, created by George) +- [ ] Snow Golems (magical snow creatures, Minecraft-like but white and faceless) + +## Quick Creation Commands + +To create remaining entities quickly, use these patterns: + +```bash +# For each hero: +mkdir heroes/{hero-name} +mkdir heroes/{hero-name}/photos +mkdir heroes/{hero-name}/prompts + +# For each item: +mkdir items/{item-name} +mkdir items/{item-name}/images +mkdir items/{item-name}/prompts + +# For each creature: +mkdir creatures/{creature-name} +mkdir creatures/{creature-name}/images +mkdir creatures/{creature-name}/prompts +``` + +## Template Description Files + +Use these templates for quick creation: + +### Hero Template +```markdown +# {Hero Name} - Character Description + +## Basic Information +- **Full Name**: {Name} +- **Age**: {Age} +- **Gender**: {Gender} +- **Role**: {Role} + +## Cross-References +- **World Origin**: [World:{world-name}] +- **Associates**: [Character:{associate}] + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* +``` + +### Item Template +```markdown +# {Item Name} - Item Description + +## Basic Information +- **Item Name**: {Name} +- **Type**: {Type} +- **Origin**: {Origin} + +## Cross-References +- **Found at**: [Location:{location}] +- **Owned by**: [Character:{owner}] + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* +``` + +### Creature Template +```markdown +# {Creature Name} - Creature Description + +## Basic Information +- **Creature Name**: {Name} +- **Type**: {Type} +- **Size**: {Size} +- **Threat Level**: {Level} + +## Abilities +- {Ability description} + +## Cross-References +- **World Origin**: [World:{world}] +- **Enemies**: [Character:{enemy}] + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* +``` \ No newline at end of file diff --git a/PROJECT_STANDARDS.md b/PROJECT_STANDARDS.md new file mode 100644 index 0000000..893fb0d --- /dev/null +++ b/PROJECT_STANDARDS.md @@ -0,0 +1,166 @@ +# Project Standards - Fantasy Universe Visual Guidelines + +## Universal Quality Requirements + +### Technical Standards +- **Resolution**: Minimum 1024x1024 pixels for all generated images +- **Format**: PNG for final images, JPEG acceptable for iterations +- **Aspect Ratios**: + - Character portraits: 3:4 or 1:1 + - Location shots: 16:9 or 3:2 + - Scene compositions: 16:9 or 2:1 cinematic +- **Quality Level**: Professional, publication-ready imagery + +### Visual Consistency Markers + +#### Character Requirements +- **Facial Features**: Must remain identical across all generations +- **Body Proportions**: Consistent height, build, and physical characteristics +- **Distinguishing Marks**: Scars, tattoos, birthmarks must appear consistently +- **Hair**: Color, texture, length, and style must match established descriptions +- **Clothing Style**: Character-appropriate attire reflecting their role and world + +#### Location Requirements +- **Architectural Style**: Must align with established world-building guidelines +- **Color Palette**: Consistent environmental colors and lighting +- **Scale and Proportions**: Realistic and consistent building/landscape sizes +- **Signature Elements**: Unique identifying features that make locations recognizable + +## Art Style Guidelines + +### Primary Visual Style +**Fantasy Realism with Cinematic Quality** +- Photorealistic rendering with fantasy elements seamlessly integrated +- Rich, saturated colors with dramatic lighting +- High contrast and depth of field for visual impact +- Professional photography composition principles + +### Lighting Philosophy +- **Golden Hour Preference**: Warm, dramatic lighting for most scenes +- **Atmospheric Lighting**: Volumetric effects, god rays, and environmental ambiance +- **Character Lighting**: Three-point lighting setup for portraits +- **Location Lighting**: Natural environmental lighting with enhancement + +### Color Palette Framework + +#### World-Specific Palettes +**Urban/Civilization Areas:** +- Primary: Warm earth tones (browns, golds, bronze) +- Secondary: Deep blues and purples for magical elements +- Accent: Bright metallics (gold, silver, copper) + +**Natural/Wilderness Areas:** +- Primary: Rich greens and earth browns +- Secondary: Sky blues and cloud whites +- Accent: Seasonal colors (autumn reds, spring yellows) + +**Magical/Mystical Areas:** +- Primary: Deep purples and midnight blues +- Secondary: Ethereal whites and silvers +- Accent: Glowing energies (electric blue, violet, gold) + +## Character Design Standards + +### Consistency Requirements +- **Unique Identifier System**: Each character must have 3-5 distinctive features +- **Feature Hierarchy**: Primary (face, hair), Secondary (clothing, accessories), Tertiary (posture, expressions) +- **Evolution Guidelines**: Characters may age or change, but core features remain constant + +### Clothing and Accessories +- **Cultural Appropriateness**: Attire must reflect character's origin world/culture +- **Functional Design**: Clothing should serve the character's role and activities +- **Material Consistency**: Fabrics and textures appropriate to world's technology level +- **Symbolic Elements**: Rank insignia, cultural symbols, personal totems + +### Expression and Pose Guidelines +- **Personality Reflection**: Facial expressions and body language must match character personality +- **Scene Appropriateness**: Emotions and reactions suitable to narrative context +- **Dynamic Composition**: Avoid static, lifeless poses +- **Interaction Awareness**: Characters should appear naturally integrated into their environment + +## Location Design Standards + +### Architectural Consistency +- **Cultural Cohesion**: Buildings reflect the civilization that created them +- **Material Logic**: Construction materials available in the world/region +- **Scale Realism**: Proportions appropriate for intended inhabitants +- **Functional Design**: Structures serve clear purposes within the world + +### Environmental Integration +- **Geographic Logic**: Landscapes consistent with established world geography +- **Climate Consistency**: Weather and seasonal effects appropriate to region +- **Ecosystem Coherence**: Flora and fauna suitable to the environment +- **Magical Integration**: Supernatural elements naturally woven into the environment + +## Scene Composition Standards + +### Storytelling Through Imagery +- **Narrative Clarity**: The image should advance or illustrate the story +- **Emotional Resonance**: Visual mood matches narrative tone +- **Character Focus**: Clear protagonist/subject hierarchy +- **Environmental Storytelling**: Background elements support the narrative + +### Technical Composition +- **Rule of Thirds**: Strategic placement of key elements +- **Depth Layers**: Foreground, midground, background clearly defined +- **Leading Lines**: Visual elements guide viewer attention +- **Framing**: Natural frames within the scene enhance focus + +## Quality Assurance Criteria + +### Mandatory Checks +1. **Character Recognition**: Can established characters be immediately identified? +2. **Location Verification**: Does the location match established descriptions? +3. **Style Consistency**: Does the image align with world visual guidelines? +4. **Technical Quality**: Professional-grade execution and clarity? +5. **Narrative Appropriateness**: Does the image serve the story? + +### Rejection Criteria +- Character features don't match established descriptions +- Location elements contradict world-building guidelines +- Art style deviates from established visual framework +- Technical quality below professional standards +- Narrative disconnect with established story context + +## Iterative Improvement Framework + +### Version Control +- **V1**: Initial generation following base prompt +- **V2**: First iteration addressing primary issues +- **V3**: Refinement focusing on consistency and quality +- **Final**: Approved version meeting all standards + +### Improvement Priorities +1. **Character Consistency** (highest priority) +2. **Location Accuracy** +3. **Style Alignment** +4. **Technical Quality** +5. **Narrative Enhancement** + +### Documentation Requirements +- Archive successful prompts for pattern recognition +- Document failed approaches to avoid repetition +- Maintain consistency logs for character and location evolution +- Track style guide refinements and updates + +## Special Considerations + +### Cross-Scene Continuity +- Characters must appear consistent across different locations +- Locations must maintain their identity across different scenes +- Time progression should be visually coherent (aging, seasonal changes) +- Magical or supernatural elements should follow established rules + +### Cultural Sensitivity +- Fantasy cultures should be internally consistent +- Avoid real-world cultural appropriation in costume and architecture +- Respect the internal logic of created civilizations +- Maintain dignity in character representation + +### Technology Integration +- Use available tools (reference images, style guides) effectively +- Leverage prompt engineering best practices +- Maintain backup and version control +- Document successful workflows for replication + +This standards document serves as the foundation for all visual generation within the fantasy universe project, ensuring consistent, high-quality imagery that supports and enhances the narrative experience. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f92df56 --- /dev/null +++ b/README.md @@ -0,0 +1,162 @@ +# Magic Building - Fantasy Universe Visual Generation + +A comprehensive fantasy universe project designed for consistent visual generation using Gemini Flash Image (Nano Banana) through Claude Code and Nano-Banana-MCP integration. + +## Project Status + +### ✅ Completed Setup +- **Framework Files**: CLAUDE.md, PROJECT_STANDARDS.md +- **World Structure**: 7 worlds with descriptions and style guides +- **Core Locations**: 6 key locations with descriptions +- **Key Characters**: Main protagonists and antagonists +- **Essential Items**: Magical staffs and artifacts +- **Dangerous Creatures**: Boss-level threats + +### 📋 Entities Created + +#### Worlds (7/7) +- Modern World +- Winter World +- Giant Snails World +- Kurnog World +- Skeleton World +- Twilight World +- Camelot World + +#### Locations (6/6) +- Gronin (modern city) +- Source Castle +- Guardian Library +- Abandoned Building +- Quantum Lab Geneva +- Academy Town Geneva + +#### Sample Heroes (4/16) +- Dan (13 yo boy) +- Nick (14 yo boy) +- Camelot (54 yo, Chief Mage) +- Eliot (18 yo, mage, son of Camelot) +- Konstantin (54 yo, quantum physicist) + +#### Sample Items (2/9) +- Camelot Staff (high mage staff with green crystal) +- Mystical Staff (ultimate power, minimalist design) + +#### Sample Creatures (2/11) +- Skeleton Spider (10m height, extremely dangerous) +- Ice Dragon (ice plasma breath) + +## Quick Start Guide + +### 1. Installation +Ensure you have: +- Claude Code installed +- Nano-Banana-MCP configured: https://github.com/ConechoAI/Nano-Banana-MCP +- Access to Gemini Flash Image API + +### 2. Usage Examples + +Generate a character in a location: +``` +Generate Archmage Camelot standing in the Central Square of Grenoble +``` + +Create character with item: +``` +Show Eliot wielding the Mystical Staff in the Guardian Library +``` + +Battle scene: +``` +Create Camelot fighting the Skeleton Spider in the Abandoned Building +``` + +### 3. How It Works + +1. **Claude Code parses** your request for entities +2. **Auto-gathers context** from description files and cross-references +3. **Builds comprehensive prompt** following Nano Banana best practices +4. **Generates 3-4 variants** using optimized prompting +5. **Filters and presents** 2 best options +6. **Iterates until approval** with prompt refinement +7. **Archives successful** prompts and images + +### 4. Entity Relationship System + +Entities are linked using standardized syntax: +- `[Character:name]` - Links to characters +- `[Location:name]` - Links to locations +- `[World:name]` - Links to worlds +- `[Item:name]` - Links to items +- `[Creature:name]` - Links to creatures + +Examples: +- `[Character:camelot] (father of this character)` +- `[Item:mystical-staff] (can be wielded by this character)` +- `[Creature:ice-dragon] (defeated by this character)` + +## Completion Instructions + +### Remaining Work +See `ENTITIES_CHECKLIST.md` for complete list of entities to create. + +### Quick Creation Commands +```bash +# Create remaining heroes (12 more) +# Create remaining items (7 more) +# Create remaining creatures (9 more) +``` + +### File Templates +Use the templates in `ENTITIES_CHECKLIST.md` for consistent entity creation. + +## Visual Style Guidelines + +### Core Principles +- **Photorealistic fantasy** with cinematic quality +- **Rich, saturated colors** with dramatic lighting +- **Professional composition** following photography principles +- **World-specific consistency** in style and palette + +### Image Specifications +- **Resolution**: 1024x1024 minimum +- **Formats**: PNG for finals, JPEG for iterations +- **Aspect Ratios**: 3:4 portraits, 16:9 landscapes, 2:1 cinematic + +## Advanced Features + +### Cross-Reference Resolution +- Automatic loading of linked entities +- Relationship context in prompts +- Combat history integration +- Item-character compatibility checks + +### Iterative Improvement +- Quality filtering based on consistency +- Failure analysis and prompt refinement +- Pattern recognition from successful generations +- Archived prompt reuse + +### Batch Processing +- Multiple related generations +- Context continuity across images +- Metadata updates in batches + +## Support + +### Framework Files +- `CLAUDE.md` - Complete usage framework +- `PROJECT_STANDARDS.md` - Quality and style requirements +- `ENTITIES_CHECKLIST.md` - Remaining work and templates + +### Troubleshooting +- Check entity file existence before generation +- Verify cross-references resolve correctly +- Ensure world style guides are properly linked +- Review archived prompts for pattern guidance + +--- + +**Ready to create stunning, consistent fantasy visuals!** 🎨✨ + +Start with: `"Generate Camelot casting a spell in the Central Square of Grenoble"` \ No newline at end of file diff --git a/SETTINGS_GUIDE.md b/SETTINGS_GUIDE.md new file mode 100644 index 0000000..e4fb997 --- /dev/null +++ b/SETTINGS_GUIDE.md @@ -0,0 +1,192 @@ +# Settings System - Style Reference Guide + +## Overview +The Settings system provides reusable visual style references that can be applied across multiple characters, worlds, and scenarios. These are **thematic style guides** rather than specific entities, designed to ensure consistent visual aesthetics across the universe. + +## Available Setting Categories + +### 📗 Clothing (settings/clothing/) +Visual style references for character attire across different worlds and scenarios. + +#### Created Examples: +- **ancient-mage-robes** - Traditional high-status magical practitioner attire + - Flowing robes, rich fabrics, runic embroidery + - Perfect for [Character:camelot], [Character:eliot], high-ranking mages + +- **modern-tactical-gear** - Contemporary military/security equipment + - Functional tactical clothing, protective gear, modern materials + - Suitable for [World:modern-world] action scenarios + +#### Suggested Additions: +- **medieval-noble-attire** - Royal and aristocratic clothing +- **casual-modern-wear** - Contemporary everyday clothing +- **winter-survival-gear** - Cold weather protective clothing +- **scholar-robes** - Academic and research attire + +### 🚗 Transportation (settings/transportation/) +Vehicle and mount styles for different worlds and scenarios. + +#### Created Examples: +- **magical-mounts** - Fantasy creature transportation + - Dragons, unicorns, winged horses, magical steeds + - Perfect for [World:camelot-world] and fantasy travel + +#### Suggested Additions: +- **modern-vehicles** - Contemporary cars, motorcycles, aircraft +- **medieval-horses** - Traditional horseback transportation +- **futuristic-transport** - Advanced sci-fi transportation +- **naval-vessels** - Ships and boats for water travel + +### ⚔️ Weapons (settings/weapons/) +Weapon styles and designs for different combat scenarios. + +#### Suggested Content: +- **medieval-weapons** - Swords, shields, crossbows, traditional arms +- **modern-firearms** - Contemporary weapons and tactical equipment +- **magical-weapons** - Enchanted and mystical weapons +- **futuristic-weapons** - Advanced technology armaments + +### 🌲 Environments (settings/environments/) +Background and environmental style references. + +#### Suggested Content: +- **magical-forests** - Enchanted woodland environments +- **urban-landscapes** - Modern city environments +- **ancient-ruins** - Historical and archaeological sites +- **winter-landscapes** - Cold weather and snow environments + +### 🏰 Architecture Styles (settings/architecture-styles/) +Building and structure design patterns. + +#### Suggested Content: +- **medieval-castles** - Traditional fortress and castle designs +- **modern-buildings** - Contemporary architectural styles +- **magical-towers** - Fantasy magical structure designs +- **ancient-temples** - Religious and ceremonial architecture + +### ✨ Magical Effects (settings/magical-effects/) +Visual effect styles for magical phenomena. + +#### Suggested Content: +- **elemental-magic** - Fire, water, earth, air magical visualizations +- **healing-magic** - Positive magical effect visualizations +- **dark-magic** - Shadow and necromantic magical effects +- **protective-magic** - Barrier and shielding magical effects + +## How Settings Work + +### Automatic Application +Claude Code automatically applies appropriate settings based on: +- **Character Status**: High-ranking characters get more elaborate styles +- **World Context**: Settings must match the world's technology/magic level +- **Scenario Requirements**: Combat, formal, casual, travel scenarios need different styles +- **Character Preferences**: Established style preferences from character descriptions + +### Cross-References Integration +Settings can be explicitly referenced in entity descriptions: +```markdown +## Cross-References +- **Typical Attire**: [Setting:clothing/ancient-mage-robes] +- **Preferred Transportation**: [Setting:transportation/magical-mounts] +- **Combat Style**: [Setting:weapons/magical-weapons] +``` + +### Style Override Commands +Users can request specific style applications: +- `"Style Camelot in modern tactical gear"` - Apply unusual style for contrast +- `"Show Eliot in ancient mage robes"` - Apply formal attire +- `"Generate Nataly in winter survival gear"` - Apply environmental clothing + +## Creating New Settings + +### File Structure Template +``` +settings/{category}/{style-name}/ +├── description.md # Comprehensive style guide +├── images/ # Reference images for the style +└── prompts/ # Successful prompts using this style +``` + +### Description Template +```markdown +# {Style Name} - {Category} Setting + +## Basic Information +- **Setting Name**: {Style Name} +- **Category**: {Category} +- **Style Period**: {Time period/aesthetic} +- **Application**: {When/who uses this style} + +## Visual Characteristics +[Detailed visual description] + +## Applicable Worlds and Characters +[Cross-references to compatible entities] + +## Usage Guidelines +[How and when to apply this style] + +## Prompt Integration Notes +[Keywords and phrases for prompt generation] +``` + +## Style Combination Rules + +### Compatible Combinations +- **ancient-mage-robes** + **magical-mounts** = Classic high fantasy aesthetic +- **modern-tactical-gear** + **modern-vehicles** = Contemporary action scenario +- **winter-survival-gear** + **winter-landscapes** = Cold environment survival + +### Incompatible Combinations +- **ancient-mage-robes** + **modern-vehicles** = Avoid unless specifically requested +- **modern-tactical-gear** + **magical-mounts** = Requires careful narrative justification +- **medieval-weapons** + **futuristic-environments** = Only for specific crossover scenarios + +## Quality Standards + +### Visual Consistency +- Settings must align with established world aesthetics +- Character status should be reflected in style complexity +- Environmental appropriateness is essential + +### Narrative Appropriateness +- Styles must serve the story and character development +- Anachronistic combinations require narrative justification +- Cultural sensitivity in style design and application + +### Technical Standards +- All settings follow PROJECT_STANDARDS.md requirements +- High-quality reference materials and detailed descriptions +- Successful prompt patterns documented for reuse + +## Integration with Existing Entities + +### Character Applications +- **[Character:camelot]**: ancient-mage-robes, magical-mounts, magical-weapons +- **[Character:nataly]**: modern-casual-wear, modern-vehicles, modern-environments +- **[Character:eliot]**: ancient-mage-robes (simpler), magical-mounts, apprentice-weapons + +### World Compatibility +- **[World:camelot-world]**: All magical and medieval settings appropriate +- **[World:modern-world]**: Contemporary settings only +- **[World:winter-world]**: Winter-themed settings, magical ice effects + +### Location Enhancement +- **[Location:central-castle]**: medieval-architecture, magical-effects, ancient-weapons +- **[City:gronin]**: modern-architecture, urban-environments, contemporary-styles + +## Future Expansion + +### Priority Categories +1. **Weapons** - Essential for combat scenarios +2. **Environments** - Critical for location consistency +3. **Architecture Styles** - Important for location and world building +4. **Magical Effects** - Key for fantasy world visualization + +### Style Suggestions +- **Steampunk Elements** - For worlds mixing magic and technology +- **Cyberpunk Aesthetics** - For futuristic modern world scenarios +- **Post-Apocalyptic** - For destroyed world environments +- **Underwater Themes** - For aquatic world and creature scenarios + +The Settings system ensures that every generated image maintains high visual quality and narrative consistency while providing flexibility for creative storytelling across the universe. \ No newline at end of file diff --git a/cities/grenobl/description.md b/cities/grenobl/description.md new file mode 100644 index 0000000..3b9f2a1 --- /dev/null +++ b/cities/grenobl/description.md @@ -0,0 +1,143 @@ +# Grenoble - Medieval Fantasy City + +## Basic Information +- **City Name**: Grenoble +- **Type**: Fortified medieval fantasy city +- **World**: [World:camelot-world] +- **Government**: Mage Guild Council +- **Population**: Mixed magical and non-magical citizens +- **Primary Function**: Center of magical learning and knightly orders + +## Architectural Signature Elements (NEVER CHANGE) + +### Core Structures +- **Central Castle**: Massive stone castle with twin cylindrical towers topped with crenellated battlements +- **Defensive Walls**: Thick stone walls with regular watchtowers on three sides +- **Stone Bridge**: Wide multi-arched bridge crossing the defensive river +- **Main Gates**: Massive fortified entrance flanked by garrison watchtowers + +### Distinctive Visual Markers +- **Twin Towers**: Iconic cylindrical towers dominating the city skyline +- **Weathered Sandstone**: Primary building material creating warm, aged appearance +- **Terra Cotta Roofs**: Distinctive red-orange clay tile roofing throughout the city +- **Cobblestone Streets**: Narrow winding medieval streets in organic pattern +- **Timber Framing**: Traditional medieval construction with exposed wooden frameworks + +### Material Palette +- **Stone**: Weathered sandstone for walls and foundations +- **Wood**: Dark timber framing and shutters +- **Roofing**: Red-orange terra cotta clay tiles +- **Metalwork**: Iron fixtures and defensive elements + +## Districts and Locations + +### Central Castle District +- **[Location:central-castle]**: Mage Guild headquarters and [Character:camelot]'s residence +- **Castle Grounds**: Training chambers, laboratories, libraries, council halls +- **Magical Infrastructure**: Enchanted facilities for magical research and education + +### Civic Center +- **[Location:central-square]**: Main town square with town hall as focal point +- **Commercial District**: Traditional markets and merchant establishments +- **Administrative Buildings**: Civic governance and guild offices + +### Residential Districts +- **Noble Quarter**: Higher-status residences near the castle +- **Artisan District**: Craftsmen and magical item creators +- **Common Quarter**: General population housing + +### Defensive Perimeter +- **[Location:main-gates]**: Primary fortified entrance with garrison +- **Watchtowers**: Regular defensive posts along the walls +- **River Boundary**: Natural defense on fourth side + +## Transportation Network + +### Primary Routes +- **Main Thoroughfare**: Bridge → Main Gates → Central Square → Castle entrance +- **Secondary Streets**: Organic medieval street network branching from main route +- **Waterway Access**: River provides trade and transportation routes + +### Bridge System +- **Stone Bridge**: Multi-arched defensive bridge with strategic importance +- **Moat Crossing**: Controlled access point for all land-based entry + +## Society and Culture + +### Population Composition +- **Magical Practitioners**: Mages, apprentices, magical researchers +- **Knights and Guards**: Military orders and city defense +- **Craftsmen**: Artisans specializing in magical and mundane goods +- **Merchants**: Trade specialists and shop owners +- **Common Citizens**: General population supporting the magical community + +### Cultural Focus +- **Magical Education**: Primary center for magical learning and advancement +- **Martial Traditions**: Knightly orders and combat training +- **Craftsmanship**: High-quality magical and mundane item production +- **Community Integration**: Harmonious coexistence of magical and non-magical citizens + +## Environmental Characteristics + +### Natural Features +- **Defensive River**: Wide flowing river providing protection and water source +- **Elevated Position**: Castle positioned on high ground for defense and visibility +- **Surrounding Landscape**: Medieval countryside with agricultural support + +### Climate and Atmosphere +- **Temperate Climate**: Suitable for year-round habitation and agriculture +- **Magical Ambiance**: Subtle magical energy throughout the city +- **Medieval Authenticity**: Genuine medieval atmosphere with fantasy integration + +## Visual Generation Guidelines + +### Preferred Camera Angles +- **Castle Overview**: Elevated shots showing twin towers and city layout +- **Street Level**: Ground perspective showing medieval architecture and daily life +- **Bridge Approach**: Dramatic view of fortified entrance from bridge +- **Central Square**: Community gathering space with town hall focal point + +### Lighting Recommendations +- **Golden Hour**: Warm lighting on sandstone creates beautiful contrast +- **Evening**: Magical illumination from castle and guild facilities +- **Daytime**: Clear lighting showing architectural details and bustling activity + +### Seasonal Variations +- **Spring/Summer**: Vibrant colors, active street life, clear skies +- **Autumn**: Warm colors complementing terra cotta roofs +- **Winter**: Light snow on roofs, warm glows from windows + +## Cross-References + +### Residents +- **[Character:camelot]**: Chief Mage, lives in central castle +- **[Character:eliot]**: Son of Camelot, initiated mage +- **[Character:bart]**: Young mage, friend of Eliot + +### Key Locations +- **[Location:central-castle]**: Mage Guild headquarters and Camelot's residence +- **[Location:central-square]**: Main civic and commercial center +- **[Location:main-gates]**: Primary defensive entrance + +### Associated Items +- **[Item:camelot-staff]**: Wielded by the city's chief mage +- **[Item:apprentice-staff]**: Used by mage students in the guild + +### World Context +- **[World:camelot-world]**: Native realm with high magical civilization + +## Reference Image Status +- **City Overview**: [Pending - wide shot showing castle and layout] +- **Castle Detail**: [Pending - close-up of twin towers and architecture] +- **Street Scene**: [Pending - medieval street life and buildings] +- **Bridge Approach**: [Pending - dramatic entrance view] + +## Subdirectories +- `images/` - Generated city images +- `prompts/` - Successful prompts archive +- `locations/` - Detailed descriptions of specific locations within the city + +--- +*Last Updated: [Date]* +*Visual Consistency Level: LOCKED - Core architectural elements cannot be changed* +*Established as home city of Archmage Camelot and center of magical civilization* \ No newline at end of file diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 2_03PM (1).jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 2_03PM (1).jpeg new file mode 100644 index 0000000..bac6c01 Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 2_03PM (1).jpeg differ diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 2_36PM.jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 2_36PM.jpeg new file mode 100644 index 0000000..9e65e30 Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 2_36PM.jpeg differ diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 2_43PM (2).jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 2_43PM (2).jpeg new file mode 100644 index 0000000..fca8388 Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 2_43PM (2).jpeg differ diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (1).jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (1).jpeg new file mode 100644 index 0000000..9ba4033 Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (1).jpeg differ diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (2).jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (2).jpeg new file mode 100644 index 0000000..d91293a Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 2_44PM (2).jpeg differ diff --git a/cities/grenobl/images/Generated Image September 07, 2025 - 3_05PM.jpeg b/cities/grenobl/images/Generated Image September 07, 2025 - 3_05PM.jpeg new file mode 100644 index 0000000..eefb75b Binary files /dev/null and b/cities/grenobl/images/Generated Image September 07, 2025 - 3_05PM.jpeg differ diff --git a/cities/grenobl/locations/central-castle.md b/cities/grenobl/locations/central-castle.md new file mode 100644 index 0000000..6f13d32 --- /dev/null +++ b/cities/grenobl/locations/central-castle.md @@ -0,0 +1,66 @@ +# Central Castle - Location Description + +## Basic Information +- **Location Name**: Central Castle +- **Type**: Mage Guild headquarters and residence +- **City**: [City:grenoble] +- **World**: [World:camelot-world] +- **Function**: Magical education, research, and governance center + +## Architectural Signature Elements (NEVER CHANGE) + +### Core Structures +- **Twin Cylindrical Towers**: Iconic paired towers with crenellated battlements +- **Weathered Sandstone Construction**: Massive stone blocks creating imposing fortress +- **Main Keep**: Central residential and administrative building +- **Guild Halls**: Specialized chambers for magical council meetings + +### Interior Facilities +- **Archmage's Residence**: Private quarters for [Character:camelot] +- **Extensive Libraries**: Vast collections of magical knowledge and research +- **Magical Laboratories**: Equipped facilities for magical experimentation +- **Training Chambers**: Practice spaces for magical and combat instruction +- **Council Halls**: Meeting rooms for guild deliberations and decisions + +### Distinctive Features +- **Elevated Position**: Positioned on high ground dominating city skyline +- **Magical Infrastructure**: Enchanted facilities integrated throughout structure +- **Defensive Design**: Military architecture adapted for magical community +- **Tower Visibility**: Twin towers serve as landmarks visible throughout region + +## Daily Operations + +### Guild Activities +- **Magical Education**: Training of apprentice mages and advanced practitioners +- **Research Projects**: Ongoing magical experimentation and development +- **Council Meetings**: Guild governance and policy decisions +- **Community Services**: Magical assistance to city and surrounding areas + +### Residential Function +- **Archmage's Quarters**: Private residence of [Character:camelot] +- **Guest Accommodations**: Facilities for visiting dignitaries and scholars +- **Staff Housing**: Living quarters for guild personnel and servants + +## Visual Generation Guidelines + +### Preferred Angles +- **Exterior Overview**: Show twin towers and imposing fortress structure +- **Courtyard Views**: Interior spaces showing magical activities +- **Tower Details**: Close-ups of architectural features and magical elements +- **Throne Room/Council**: Interior shots of important ceremonial spaces + +### Lighting Characteristics +- **Magical Illumination**: Soft glows from enchanted lighting systems +- **Natural Light**: Large windows providing bright interior illumination +- **Evening Atmosphere**: Warm lights creating welcoming magical ambiance + +## Cross-References +- **Primary Resident**: [Character:camelot] (Archmage) +- **Regular Visitors**: [Character:eliot], [Character:bart] +- **Associated Items**: [Item:camelot-staff], [Item:archmage-staff] +- **Parent City**: [City:grenoble] +- **World Context**: [World:camelot-world] + +--- +*Last Updated: [Date]* +*Consistency Level: LOCKED - Architectural signature elements established* \ No newline at end of file diff --git a/cities/grenobl/locations/central-square.md b/cities/grenobl/locations/central-square.md new file mode 100644 index 0000000..2825634 --- /dev/null +++ b/cities/grenobl/locations/central-square.md @@ -0,0 +1,71 @@ +# Central Square - Location Description + +## Basic Information +- **Location Name**: Central Square +- **Type**: Main civic and commercial center +- **City**: [City:grenoble] +- **World**: [World:camelot-world] +- **Function**: Town hall, markets, community gathering space + +## Architectural Signature Elements (NEVER CHANGE) + +### Core Structures +- **Town Hall**: Central civic building serving as focal point of the square +- **Cobblestone Plaza**: Traditional medieval paving with weathered stone +- **Surrounding Buildings**: Timber-framed structures with terra cotta roofs +- **Market Stalls**: Traditional medieval commercial infrastructure + +### Distinctive Features +- **Open Layout**: Spacious plaza allowing for community gatherings +- **Medieval Architecture**: Consistent timber-framed buildings with period details +- **Central Positioning**: Located on main thoroughfare between gates and castle +- **Commercial Integration**: Markets and shops integrated into surrounding structures + +## Daily Activities + +### Civic Functions +- **Town Governance**: Administrative activities in town hall +- **Public Announcements**: Official proclamations and community notices +- **Legal Proceedings**: Civil matters and dispute resolution +- **Community Meetings**: Gatherings for local issues and celebrations + +### Commercial Activities +- **Daily Markets**: Regular trading of goods and provisions +- **Artisan Sales**: Local craftsmen displaying and selling their work +- **Merchant Trading**: Commercial exchanges and business dealings +- **Seasonal Fairs**: Special events and festival markets + +### Social Functions +- **Community Gatherings**: Social events and public celebrations +- **Cultural Events**: Performances, storytelling, and entertainment +- **Religious Observances**: Ceremonial activities and festivals +- **Information Exchange**: News sharing and social interaction + +## Visual Generation Guidelines + +### Preferred Angles +- **Square Overview**: Wide shots showing town hall and surrounding buildings +- **Market Activity**: Street-level views of daily commercial life +- **Architectural Details**: Close-ups of medieval building features +- **Community Events**: Scenes of gatherings and celebrations + +### Activity Levels +- **Busy Market Day**: Crowded with merchants, customers, and daily activity +- **Quiet Morning**: Peaceful early hours with minimal activity +- **Festival Time**: Celebration scenes with decorations and festivities +- **Evening Calm**: Sunset lighting with people returning home + +### Lighting Recommendations +- **Natural Daylight**: Clear lighting showing architectural details +- **Golden Hour**: Warm lighting on timber and stone creating atmospheric glow +- **Market Ambiance**: Busy daytime lighting with shadows and activity + +## Cross-References +- **Parent City**: [City:grenoble] +- **Main Route**: Located on thoroughfare from [Location:main-gates] to [Location:central-castle] +- **World Context**: [World:camelot-world] +- **Nearby Residents**: [Character:camelot], [Character:eliot], [Character:bart] + +--- +*Last Updated: [Date]* +*Consistency Level: LOCKED - Medieval architecture and layout established* \ No newline at end of file diff --git a/cities/grenobl/locations/main-gates.md b/cities/grenobl/locations/main-gates.md new file mode 100644 index 0000000..0de52c7 --- /dev/null +++ b/cities/grenobl/locations/main-gates.md @@ -0,0 +1,87 @@ +# Main Gates - Location Description + +## Basic Information +- **Location Name**: Main Gates +- **Type**: Fortified city entrance +- **City**: [City:grenoble] +- **World**: [World:camelot-world] +- **Function**: Primary defensive entrance and checkpoint + +## Architectural Signature Elements (NEVER CHANGE) + +### Core Structures +- **Massive Gate Structure**: Imposing fortified entrance with thick stone construction +- **Flanking Watchtowers**: Twin towers housing city garrison on either side of gates +- **Stone Bridge Approach**: Wide multi-arched bridge crossing defensive moat +- **Portcullis System**: Heavy iron gate providing additional security layer +- **Guard Quarters**: Integrated barracks and defensive facilities + +### Defensive Features +- **Thick Stone Walls**: Continuation of city's defensive perimeter +- **Murder Holes**: Defensive openings in gate ceiling for protection +- **Arrow Slits**: Strategic openings for defensive archery +- **Reinforced Doors**: Heavy wooden gates reinforced with iron bands +- **Moat Crossing**: Controlled bridge access with defensive positioning + +### Bridge Architecture +- **Multi-Arched Design**: Stone bridge with multiple supporting arches +- **Defensive Width**: Wide enough for trade wagons but controllable +- **Strategic Position**: Only land-based access point to the city +- **River Crossing**: Spans the defensive river boundary + +## Daily Operations + +### Security Functions +- **Gate Guard Duty**: Continuous security presence and visitor monitoring +- **Customs Inspection**: Examination of goods and travelers entering city +- **Traffic Control**: Managing flow of people, goods, and animals +- **Emergency Response**: First line of defense against external threats + +### Commercial Activities +- **Trade Inspection**: Verification of merchant goods and documentation +- **Toll Collection**: Fees for city access and market privileges +- **Traveler Services**: Information and assistance for visitors +- **Accommodation Referrals**: Directing visitors to appropriate lodging + +## Guard Operations + +### Personnel +- **Gate Captain**: Senior officer commanding gate security +- **Watchmen**: Regular guards maintaining security shifts +- **Customs Officers**: Specialists handling trade and taxation +- **Messenger Service**: Communication with castle and other city areas + +### Procedures +- **Visitor Screening**: Evaluation of entering persons and purposes +- **Goods Inspection**: Examination of trade materials and contraband detection +- **Emergency Protocols**: Procedures for threats and city lockdown +- **Record Keeping**: Documentation of significant entries and events + +## Visual Generation Guidelines + +### Preferred Angles +- **Bridge Approach**: Dramatic view showing full gate structure and defensive position +- **Gate Detail**: Close-up shots of architectural features and defensive elements +- **Guard Activity**: Scenes showing daily security and inspection operations +- **Overhead View**: Strategic perspective showing bridge, moat, and defensive layout + +### Activity Scenarios +- **Busy Day**: Multiple travelers, merchants, and guards active +- **Inspection Scene**: Detailed examination of goods or suspicious visitors +- **Evening Watch**: Quiet guard duty with atmospheric lighting +- **Emergency Alert**: Defensive preparations or threat response + +### Lighting Recommendations +- **Daytime Security**: Clear lighting showing all defensive features +- **Evening Watch**: Torch and lamplight creating atmospheric security scene +- **Dawn Patrol**: Early morning light with changing of guard + +## Cross-References +- **Parent City**: [City:grenoble] +- **Connected Route**: Main thoroughfare leading to [Location:central-square] and [Location:central-castle] +- **World Context**: [World:camelot-world] +- **Defensive Network**: Part of comprehensive city fortification system + +--- +*Last Updated: [Date]* +*Consistency Level: LOCKED - Defensive architecture and strategic positioning established* \ No newline at end of file diff --git a/cities/grenoble/description.md b/cities/grenoble/description.md new file mode 100644 index 0000000..af114a6 --- /dev/null +++ b/cities/grenoble/description.md @@ -0,0 +1,20 @@ +# Grenoble - Capital City of the Mages Guild + +## Basic Information +- **Type**: Capital City +- **World**: [World:camelot-world] +- **Time Period**: [Location:kris-era] and beyond +- **Notable Resident**: [Character:kris] (Battle Mage) + +## Overview +The major city housing the Capital Mages Guild where [Character:kris] served as a distinguished Battle Mage. As a center of magical learning and guild operations, Grenoble played a crucial role in the defense against supernatural threats during [Location:kris-era]. + +## Notable Features +- **Capital Mages Guild**: Primary magical institution where [Character:kris] held rank +- **Guild Headquarters**: Central command for magical defense operations +- **Mage Training Facilities**: Where battle mages like [Character:kris] honed their skills + +## Historical Significance +During [Location:kris-era], Grenoble served as the launching point for [Character:kris]'s various missions, including his response to the undead invasion at [Location:tri-peskary] and his resistance against [Character:supreme-mage]. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/cities/gronin/description.md b/cities/gronin/description.md new file mode 100644 index 0000000..0bf5bcc --- /dev/null +++ b/cities/gronin/description.md @@ -0,0 +1,106 @@ +# Gronin - Modern City + +## Basic Information +- **City Name**: Gronin +- **Type**: Contemporary urban center +- **World**: [World:modern-world] +- **Population**: Mixed urban population +- **Primary Function**: Modern industrial and research city + +## Urban Characteristics + +### Architecture and Infrastructure +- **Building Types**: Modern skyscrapers, office buildings, residential complexes +- **Infrastructure**: Advanced transportation, utilities, and communication systems +- **Urban Planning**: Contemporary city layout with zoned districts +- **Technology Level**: 21st century standards with modern amenities + +### Distinctive Features +- **Skyline**: Modern cityscape with high-rise buildings +- **Transportation**: Public transit, highways, urban mobility systems +- **Commercial Districts**: Shopping centers, business complexes, financial districts +- **Residential Areas**: Modern neighborhoods and apartment complexes + +## Districts and Areas + +### Commercial Center +- **Business District**: Corporate offices and financial institutions +- **Shopping Areas**: Retail centers and commercial establishments +- **Service Sector**: Restaurants, entertainment, and urban services + +### Industrial Zone +- **Manufacturing**: Modern industrial facilities +- **Research Facilities**: Science and technology research centers +- **Logistics**: Transportation and distribution hubs + +### Residential Districts +- **Urban Neighborhoods**: Modern housing developments +- **Apartment Complexes**: High-density residential buildings +- **Suburban Areas**: Lower-density residential zones + +## Society and Culture + +### Population Composition +- **Professionals**: Scientists, engineers, business professionals +- **Industrial Workers**: Manufacturing and technical personnel +- **Service Workers**: Retail, hospitality, and urban services +- **Researchers**: Academic and corporate research staff + +### Economic Focus +- **Industry**: Modern manufacturing and production +- **Research**: Scientific and technological advancement +- **Commerce**: Urban trade and business activities +- **Services**: Modern urban service economy + +## Environmental Characteristics + +### Urban Environment +- **Climate**: Temperate urban climate +- **Infrastructure**: Modern utilities and city services +- **Transportation**: Advanced urban mobility systems +- **Sustainability**: Contemporary environmental considerations + +## Visual Generation Guidelines + +### Preferred Angles +- **City Overview**: Wide shots showing modern skyline and urban layout +- **Street Level**: Ground perspective showing modern city life and architecture +- **Business District**: Commercial and financial district scenes +- **Residential Areas**: Modern neighborhood and living spaces + +### Lighting Recommendations +- **Natural Daylight**: Clear lighting showing architectural details and urban activity +- **Evening**: City lights and urban illumination +- **Night**: Urban nightscape with building lights and street lighting + +### Activity Scenarios +- **Business Hours**: Active commercial and professional activity +- **Rush Hour**: Transportation and commuter scenes +- **Evening Life**: Urban entertainment and social activities +- **Quiet Hours**: Peaceful residential and park areas + +## Cross-References + +### Residents +- **[Character:nataly]**: Scientist and researcher, works in city laboratory + +### World Context +- **[World:modern-world]**: Contemporary Earth-like reality with modern technology + +### Related Locations +- **Laboratory Facilities**: Modern research and development centers where [Character:nataly] works + +## Reference Image Status +- **City Overview**: [Pending - modern skyline and urban landscape] +- **Business District**: [Pending - commercial and office areas] +- **Residential Areas**: [Pending - modern neighborhoods] +- **Street Scenes**: [Pending - urban life and activity] + +## Subdirectories +- `images/` - Generated city images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Visual Consistency Level: STANDARD - Modern urban environment* +*Contemporary city in modern world setting* \ No newline at end of file diff --git a/creatures/ice-dragon/description.md b/creatures/ice-dragon/description.md new file mode 100644 index 0000000..8dbf84a --- /dev/null +++ b/creatures/ice-dragon/description.md @@ -0,0 +1,32 @@ +# Ice Dragon - Creature Description + +## Basic Information +- **Creature Name**: Ice Dragon +- **Type**: Magical ice construct +- **Size**: Large dragon +- **Threat Level**: Dangerous +- **World Origin**: [World:winter-world] + +## Physical Description +- **Material**: Ice magical substance +- **Form**: Dragon-like creature +- **Color**: Ice blue/white + +## Abilities +- **Ice Plasma Breath**: Shoots ice plasma that can burn through thick stone walls + +## Combat Notes +- **Dangerous Opponent**: Requires experienced combatants +- **Destructive Breath**: Can destroy fortifications + +## Cross-References +- **World**: [World:winter-world] +- **Related Creatures**: [Creature:snow-dragon], [Creature:ice-birds], [Creature:snow-giants] + +## Subdirectories +- `images/` - Creature visualizations +- `prompts/` - Creature-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/creatures/skeleton-queen/description.md b/creatures/skeleton-queen/description.md new file mode 100644 index 0000000..c3f7a63 --- /dev/null +++ b/creatures/skeleton-queen/description.md @@ -0,0 +1,20 @@ +# Skeleton Queen - The Transformed Lady + +## Basic Information +- **True Identity**: [Character:lady-tamara] +- **Type**: Undead Noble/Cursed Being +- **World**: [World:camelot-world] during [Location:kris-era] +- **Encountered by**: [Character:kris] + +## Overview +The Skeleton Queen was the transformed state of [Character:lady-tamara], who had been exiled from her rightful castle inheritance by [Character:lord-venedikt]. Through unknown dark circumstances, her exile led to her transformation into this undead form. + +## Abilities +- Undead command and control +- Royal authority from her previous life +- Connection to dark magic through her transformation + +## Story Arc +[Character:kris] traveled to a remote region of the kingdom to confront what he believed to be a typical undead threat. However, upon meeting the Skeleton Queen, he discovered her true identity as the exiled Lady Tamara, revealing a deeper story of injustice and transformation. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/creatures/skeleton-spider/description.md b/creatures/skeleton-spider/description.md new file mode 100644 index 0000000..6d563f9 --- /dev/null +++ b/creatures/skeleton-spider/description.md @@ -0,0 +1,39 @@ +# Skeleton Spider - Creature Description + +## Basic Information +- **Creature Name**: Skeleton Spider +- **Type**: Undead construct +- **Size**: Huge (10 meters in height) +- **Threat Level**: Extremely dangerous +- **World Origin**: [World:skeleton-world] + +## Physical Description +- **Height**: 10 meters +- **Construction**: Made from numerous small bones +- **Form**: Giant spider-like creature +- **Material**: Assembled skeleton bones + +## Abilities +- **Green Poison Jets**: Shoots green poisonous streams +- **Poison Gas**: Releases green poisonous gas +- **Sticky Web**: Spits sticky webbing that restrains heroes +- **Giant Leg Strikes**: Can attack with massive limbs + +## Weaknesses +- **Solar Flash Spell**: Can only be defeated by solar flash spell or equivalent power + +## Combat Notes +- **Extremely Dangerous**: Requires high-level magic to defeat +- **Multiple Attack Types**: Ranged poison, melee strikes, web restraints + +## Cross-References +- **World**: [World:skeleton-world] +- **Related Creatures**: [Creature:skeleton], [Creature:skeleton-warrior] + +## Subdirectories +- `images/` - Creature visualizations +- `prompts/` - Creature-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/docs/prompting-guide.md b/docs/prompting-guide.md new file mode 100644 index 0000000..00d764e --- /dev/null +++ b/docs/prompting-guide.md @@ -0,0 +1,256 @@ +# Prompting guide and strategies + +Mastering Gemini 2.5 Flash Image Generation starts with one fundamental principle: + +Describe the scene, don't just list keywords. The model's core strength is its deep language understanding. A narrative, descriptive paragraph will almost always produce a better, more coherent image than a list of disconnected words. + +## Prompts for generating images + +The following strategies will help you create effective prompts to generate exactly the images you're looking for. + +### 1. Photorealistic scenes + +For realistic images, use photography terms. Mention camera angles, lens types, lighting, and fine details to guide the model toward a photorealistic result. + +template: + +``` +A photorealistic [shot type] of [subject], [action or expression], set in +[environment]. The scene is illuminated by [lighting description], creating +a [mood] atmosphere. Captured with a [camera/lens details], emphasizing +[key textures and details]. The image should be in a [aspect ratio] format. +``` + +example: +``` +A photorealistic close-up portrait of an elderly Japanese ceramicist with +deep, sun-etched wrinkles and a warm, knowing smile. He is carefully +inspecting a freshly glazed tea bowl. The setting is his rustic, +sun-drenched workshop. The scene is illuminated by soft, golden hour light +streaming through a window, highlighting the fine texture of the clay. +Captured with an 85mm portrait lens, resulting in a soft, blurred background +(bokeh). The overall mood is serene and masterful. Vertical portrait +orientation. +``` + + +### 2. Stylized illustrations & stickers +To create stickers, icons, or assets, be explicit about the style and request a transparent background. + +template: + +``` +A [style] sticker of a [subject], featuring [key characteristics] and a +[color palette]. The design should have [line style] and [shading style]. +The background must be transparent. +``` + +example: +``` +A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's +munching on a green bamboo leaf. The design features bold, clean outlines, +simple cel-shading, and a vibrant color palette. The background must be white. +``` + + +### 3. Accurate text in images + +Gemini excels at rendering text. Be clear about the text, the font style (descriptively), and the overall design. + +template: +``` +Create a [image type] for [brand/concept] with the text "[text to render]" +in a [font style]. The design should be [style description], with a +[color scheme]. + +``` + +example: +``` +Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. +The text should be in a clean, bold, sans-serif font. The design should +feature a simple, stylized icon of a a coffee bean seamlessly integrated +with the text. The color scheme is black and white. +``` + +### 4. Product mockups & commercial photography +Perfect for creating clean, professional product shots for e-commerce, advertising, or branding. + + +template: +``` +A high-resolution, studio-lit product photograph of a [product description] +on a [background surface/description]. The lighting is a [lighting setup, +e.g., three-point softbox setup] to [lighting purpose]. The camera angle is +a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp +focus on [key detail]. [Aspect ratio]. + +``` + +example: +``` +A high-resolution, studio-lit product photograph of a minimalist ceramic +coffee mug in matte black, presented on a polished concrete surface. The +lighting is a three-point softbox setup designed to create soft, diffused +highlights and eliminate harsh shadows. The camera angle is a slightly +elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with +sharp focus on the steam rising from the coffee. Square image. +``` + +### 5. Minimalist & negative space design + +Excellent for creating backgrounds for websites, presentations, or marketing materials where text will be overlaid. + +template: +``` +A minimalist composition featuring a single [subject] positioned in the +[bottom-right/top-left/etc.] of the frame. The background is a vast, empty +[color] canvas, creating significant negative space. Soft, subtle lighting. +[Aspect ratio]. + +``` + +example: +``` +A minimalist composition featuring a single, delicate red maple leaf +positioned in the bottom-right of the frame. The background is a vast, empty +off-white canvas, creating significant negative space for text. Soft, +diffused lighting from the top left. Square image. +``` + +### 6. Sequential art (Comic panel / Storyboard)` + +Builds on character consistency and scene description to create panels for visual storytelling. + +template: +``` +A single comic book panel in a [art style] style. In the foreground, +[character description and action]. In the background, [setting details]. +The panel has a [dialogue/caption box] with the text "[Text]". The lighting +creates a [mood] mood. [Aspect ratio]. + +``` + +example: +``` +A single comic book panel in a gritty, noir art style with high-contrast +black and white inks. In the foreground, a detective in a trench coat stands +under a flickering streetlamp, rain soaking his shoulders. In the +background, the neon sign of a desolate bar reflects in a puddle. A caption +box at the top reads "The city was a tough place to keep secrets." The +lighting is harsh, creating a dramatic, somber mood. Landscape. +``` + +## Prompts for editing images + +These examples show how to provide images alongside your text prompts for editing, composition, and style transfer. + +### 1. Adding and removing elements +Provide an image and describe your change. The model will match the original image's style, lighting, and perspective. + + +template: +``` +Using the provided image of [subject], please [add/remove/modify] [element] +to/from the scene. Ensure the change is [description of how the change should +integrate]. + +``` + +example: +``` +"Using the provided image of my cat, please add a small, knitted wizard hat +on its head. Make it look like it's sitting comfortably and matches the soft +lighting of the photo." +``` + + +### 2. Inpainting (Semantic masking) + +Conversationally define a "mask" to edit a specific part of an image while leaving the rest untouched. + + +template: +``` +Using the provided image, change only the [specific element] to [new +element/description]. Keep everything else in the image exactly the same, +preserving the original style, lighting, and composition. + +``` + +example: +``` +"Using the provided image of a living room, change only the blue sofa to be +a vintage, brown leather chesterfield sofa. Keep the rest of the room, +including the pillows on the sofa and the lighting, unchanged." +``` + +### 3. Style transfer + +Provide an image and ask the model to recreate its content in a different artistic style. + + +template: +``` +Transform the provided photograph of [subject] into the artistic style of [artist/art style]. Preserve the original composition but render it with [description of stylistic elements]. + +``` + +example: +``` +"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows." +``` + +### 4. Advanced composition: Combining multiple images + +Provide multiple images as context to create a new, composite scene. This is perfect for product mockups or creative collages. + + +template: +``` +Create a new image by combining the elements from the provided images. Take +the [element from image 1] and place it with/on the [element from image 2]. +The final image should be a [description of the final scene]. + +``` + +example: +``` +"Create a professional e-commerce fashion photo. Take the blue floral dress +from the first image and let the woman from the second image wear it. +Generate a realistic, full-body shot of the woman wearing the dress, with +the lighting and shadows adjusted to match the outdoor environment." +``` + +### 5. High-fidelity detail preservation + +To ensure critical details (like a face or logo) are preserved during an edit, describe them in great detail along with your edit request. + + +template: +``` +Using the provided images, place [element from image 2] onto [element from +image 1]. Ensure that the features of [element from image 1] remain +completely unchanged. The added element should [description of how the +element should integrate]. + +``` + +example: +``` +"Take the first image of the woman with brown hair, blue eyes, and a neutral +expression. Add the logo from the second image onto her black t-shirt. +Ensure the woman's face and features remain completely unchanged. The logo +should look like it's naturally printed on the fabric, following the folds +of the shirt." +``` + +## Best Practices +To elevate your results from good to great, incorporate these professional strategies into your workflow. + +- Be Hyper-Specific: The more detail you provide, the more control you have. Instead of "fantasy armor," describe it: "ornate elven plate armor, etched with silver leaf patterns, with a high collar and pauldrons shaped like falcon wings." +- Provide Context and Intent: Explain the purpose of the image. The model's understanding of context will influence the final output. For example, "Create a logo for a high-end, minimalist skincare brand" will yield better results than just "Create a logo." +- Iterate and Refine: Don't expect a perfect image on the first try. Use the conversational nature of the model to make small changes. Follow up with prompts like, "That's great, but can you make the lighting a bit warmer?" or "Keep everything the same, but change the character's expression to be more serious." +- Use Step-by-Step Instructions: For complex scenes with many elements, break your prompt into steps. "First, create a background of a serene, misty forest at dawn. Then, in the foreground, add a moss-covered ancient stone altar. Finally, place a single, glowing sword on top of the altar." +- Use "Semantic Negative Prompts": Instead of saying "no cars," describe the desired scene positively: "an empty, deserted street with no signs of traffic." +- Control the Camera: Use photographic and cinematic language to control the composition. Terms like wide-angle shot, macro shot, low-angle perspective. diff --git a/generated_imgs/generated-2025-09-07T18-57-01-355Z-62e32x.png b/generated_imgs/generated-2025-09-07T18-57-01-355Z-62e32x.png new file mode 100644 index 0000000..50766ca Binary files /dev/null and b/generated_imgs/generated-2025-09-07T18-57-01-355Z-62e32x.png differ diff --git a/generated_imgs/generated-2025-09-07T19-03-00-163Z-vqq02l.png b/generated_imgs/generated-2025-09-07T19-03-00-163Z-vqq02l.png new file mode 100644 index 0000000..d1fdf2c Binary files /dev/null and b/generated_imgs/generated-2025-09-07T19-03-00-163Z-vqq02l.png differ diff --git a/generated_imgs/generated-2025-09-07T19-03-33-259Z-h5gj4b.png b/generated_imgs/generated-2025-09-07T19-03-33-259Z-h5gj4b.png new file mode 100644 index 0000000..55d41e1 Binary files /dev/null and b/generated_imgs/generated-2025-09-07T19-03-33-259Z-h5gj4b.png differ diff --git a/generated_imgs/generated-2025-09-07T19-10-45-100Z-ncbiyu.png b/generated_imgs/generated-2025-09-07T19-10-45-100Z-ncbiyu.png new file mode 100644 index 0000000..e954924 Binary files /dev/null and b/generated_imgs/generated-2025-09-07T19-10-45-100Z-ncbiyu.png differ diff --git a/heroes/black-mage/description.md b/heroes/black-mage/description.md new file mode 100644 index 0000000..8221d8e --- /dev/null +++ b/heroes/black-mage/description.md @@ -0,0 +1,11 @@ +# Black Mage - Undead Summoner + +## Basic Information +- **Title**: Dark Necromancer +- **World**: [World:camelot-world] during [Location:kris-era] +- **Enemy of**: [Character:kris] + +## Overview +A powerful dark mage who initiated an undead invasion from the swamp near [Location:tri-peskary]. Summoned zombies, skeletons, and giant skeleton spiders to terrorize the village. Was ultimately stopped by [Character:kris]. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/heroes/camelot/description.md b/heroes/camelot/description.md new file mode 100644 index 0000000..47d1eca --- /dev/null +++ b/heroes/camelot/description.md @@ -0,0 +1,51 @@ +# Camelot - Character Description + +## Basic Information +- **Full Name**: Camelot +- **Age**: 54 years old +- **Gender**: Male +- **Role**: Chief Mage of the Mage Guild in Grenoble +- **World Origin**: [World:camelot-world] +- **Residence**: [City:grenoble], [Location:central-castle] + +## Physical Appearance +- **Age Group**: Middle-aged adult (54 years) +- **Gender**: Male +- **Profession**: Archmage and Guild Leader +- **Bearing**: Authoritative presence befitting his high rank + +## Magical Abilities +- **Rank**: Archmage - highest level of magical practitioner +- **Specialization**: Guild leadership and advanced magical research +- **Authority**: Commands respect of entire magical community +- **Experience**: Decades of magical practice and leadership + +## Residence and Domain +- **Home**: [Location:central-castle] in [City:grenoble] +- **Workspace**: Mage Guild headquarters with libraries, laboratories, and council halls +- **Jurisdiction**: Leadership over magical community in Grenoble and surrounding region +- **Facilities**: Access to extensive magical resources and research materials + +## Cross-References +- **Children**: [Character:eliot] (son, initiated mage) +- **Associates**: [Character:bart] (young mage under guild guidance) +- **Home City**: [City:grenoble] - fortified medieval fantasy city +- **Residence**: [Location:central-castle] - Mage Guild headquarters +- **Workplace**: [Location:central-square] - civic center where guild business occurs +- **Signature Item**: [Item:camelot-staff] - high mage staff with green crystal +- **World**: [World:camelot-world] - high fantasy magical realm +- **Guild Facilities**: Access to [Item:archmage-staff] and other guild resources + +## Leadership Role +- **Guild Management**: Oversees magical education, research, and community services +- **Community Integration**: Maintains harmony between magical and non-magical citizens +- **Political Influence**: Significant role in city governance and regional affairs +- **Mentorship**: Guides development of younger magical practitioners + +## Subdirectories +- `photos/` - Character portraits and scenes +- `prompts/` - Character-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_03PM (1).jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_03PM (1).jpeg new file mode 100644 index 0000000..bac6c01 Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_03PM (1).jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_36PM.jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_36PM.jpeg new file mode 100644 index 0000000..9e65e30 Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_36PM.jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (1).jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (1).jpeg new file mode 100644 index 0000000..814567c Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (1).jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (2).jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (2).jpeg new file mode 100644 index 0000000..fca8388 Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM (2).jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM.jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM.jpeg new file mode 100644 index 0000000..acf0da7 Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_43PM.jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (1).jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (1).jpeg new file mode 100644 index 0000000..9ba4033 Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (1).jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (2).jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (2).jpeg new file mode 100644 index 0000000..d91293a Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 2_44PM (2).jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 3_05PM.jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 3_05PM.jpeg new file mode 100644 index 0000000..eefb75b Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 3_05PM.jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 6_20PM.jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 6_20PM.jpeg new file mode 100644 index 0000000..600d70d Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 6_20PM.jpeg differ diff --git a/heroes/camelot/photos/Generated Image September 07, 2025 - 6_31PM.jpeg b/heroes/camelot/photos/Generated Image September 07, 2025 - 6_31PM.jpeg new file mode 100644 index 0000000..34d4b6d Binary files /dev/null and b/heroes/camelot/photos/Generated Image September 07, 2025 - 6_31PM.jpeg differ diff --git a/heroes/dan/description.md b/heroes/dan/description.md new file mode 100644 index 0000000..4432e75 --- /dev/null +++ b/heroes/dan/description.md @@ -0,0 +1,23 @@ +# Dan - Character Description + +## Basic Information +- **Full Name**: Dan +- **Age**: 13 years old +- **Gender**: Boy +- **Role**: Young adventurer + +## Physical Appearance +- **Age Group**: Young teenager +- **Gender**: Male + +## Cross-References +- **World Origin**: Unknown +- **Associates**: [Character:nick], [Character:tim] + +## Subdirectories +- `photos/` - Character portraits and scenes +- `prompts/` - Character-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/eliot/description.md b/heroes/eliot/description.md new file mode 100644 index 0000000..48fe23e --- /dev/null +++ b/heroes/eliot/description.md @@ -0,0 +1,49 @@ +# Eliot - Character Description + +## Basic Information +- **Full Name**: Eliot +- **Age**: 18 years old +- **Gender**: Male (yuan guy) +- **Role**: Initiated mage, son of Archmage +- **World Origin**: [World:camelot-world] +- **Residence**: [City:grenoble] + +## Physical Appearance +- **Age Group**: Young adult (18 years) +- **Gender**: Male +- **Background**: Yuan heritage +- **Status**: Recently initiated mage + +## Magical Development +- **Training Status**: Has passed magical initiation +- **Skill Level**: Junior mage with formal training +- **Potential**: Considerable ability due to heritage and training +- **Education**: Trained in [Location:central-castle] guild facilities + +## Family and Social Connections +- **Father**: [Character:camelot] - Archmage and Guild Leader +- **Heritage**: Son of the most powerful mage in the region +- **Social Position**: Privileged status within magical community +- **Expectations**: High expectations due to family legacy + +## Cross-References +- **Father**: [Character:camelot] - Chief Mage of Grenoble +- **Friends**: [Character:bart] - fellow young mage +- **Home City**: [City:grenoble] - medieval fantasy city +- **Training Location**: [Location:central-castle] - Mage Guild headquarters +- **World**: [World:camelot-world] - high fantasy magical realm +- **Community**: [Location:central-square] - civic center where he interacts with community + +## Development and Future +- **Career Path**: Following in father's footsteps in magical arts +- **Guild Relationship**: Junior member of Mage Guild +- **Community Role**: Next generation of magical leadership +- **Responsibilities**: Learning advanced magical techniques and leadership + +## Subdirectories +- `photos/` - Character portraits and scenes +- `prompts/` - Character-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_2.jpg b/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_2.jpg new file mode 100644 index 0000000..5666e06 Binary files /dev/null and b/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_2.jpg differ diff --git a/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_4.jpg b/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_4.jpg new file mode 100644 index 0000000..48754bd Binary files /dev/null and b/heroes/eliot/photos/AlbedoBase_XL_On_aged_parchment_within_the_confines_of_a_priso_4.jpg differ diff --git a/heroes/konstantin/description.md b/heroes/konstantin/description.md new file mode 100644 index 0000000..1f9b962 --- /dev/null +++ b/heroes/konstantin/description.md @@ -0,0 +1,26 @@ +# Konstantin - Character Description + +## Basic Information +- **Full Name**: Konstantin +- **Age**: 54 years old +- **Gender**: Male +- **Role**: Chief physicist of international quantum physics institute +- **World Origin**: [World:modern-world] + +## Physical Appearance +- **Age Group**: Middle-aged adult +- **Gender**: Male +- **Profession**: Quantum physicist + +## Cross-References +- **Children**: [Character:edd] (son) +- **Workplace**: [Location:quantum-lab-geneva] +- **World**: [World:modern-world] + +## Subdirectories +- `photos/` - Character portraits and scenes +- `prompts/` - Character-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/kris/description.draft.md b/heroes/kris/description.draft.md new file mode 100644 index 0000000..55eaee4 --- /dev/null +++ b/heroes/kris/description.draft.md @@ -0,0 +1,6 @@ +Крис - Боевой маг столичной гильдии магов в Гренобле +28 лет. Быстрый, атлетичный. Он отличный воин и первоклассный боевой маг. Владеет в соверсшенстве многими видами рыцарского оружия, невероятной смекалкой и фантастическими боевыми магическими возможностями. Отдельная особая черта Криса - это его особая "{интуиция боевого мага}", подсказывающая ему о происходящем вокруг, особенно об опастностях и темной магии. +Крис живет в {Гренобле} (в {мире Камелота}). Однако Крис и его история происходили задолго до основной линии повествования. По факту выясняется, что Крис это дедушка Камелота. Поэтому хоть это и тот же самый мир, мы будем поразумевать это как {времена Криса} +Крис остановил вторжение {черного мага}, когда из болота за деревней {три пескаря} с одноименной таверной начали выходить зомби, скелеты и огромные скелеты-пауки. Жители деревни не моги сами оказать достойное сопротивление вторжению или позвать на помощь тк им никто не верил. Но Крис оказался рядом и спас свой мир от вторжения. +Кроме того, Крис, его друзья и другие примкнувшие к нему маги, оказали сопротивление и непокорность {Верховному Магу} который собирался устроить армагеддон и стереть с лица земли всю деревню и болото из которого выходила нечесть. Чтобы остановить начавшийся армагеддон, созданный главным магом, Крис с друзьями замедлил время и создал кокон вокруг армагеддона, аккуратно опустил его на повехность озера, и спрятал создав сверху поле с травой. Однако это хоть и замедлило процесс но не остановило проблему, решать которую придется следующим поколениям +В следующей части Крис отравляется сражаться с {Королевой Скелетов} в одаленном районе своего королевства. Он знакомится с королевой, которой на самом деле является {Леди Тамара} - наследница замка, которую выгнал и пустил по миру {Лорд Венедикт}, являющийсся лучшим другом и советником {Верховного Мага}. diff --git a/heroes/kris/description.md b/heroes/kris/description.md new file mode 100644 index 0000000..d9e1196 --- /dev/null +++ b/heroes/kris/description.md @@ -0,0 +1,57 @@ +# Kris - Battle Mage of the Capital Guild + +## Basic Information +- **Age**: 28 years old +- **Title**: Battle Mage of the Capital Mages Guild in [City:grenoble] +- **World**: [World:camelot-world] (during [Location:kris-era]) +- **Relationship**: Grandfather of [Character:camelot] + +## Physical Description +Kris is a quick and athletic warrior-mage with an imposing presence. He has dark hair and a well-groomed beard, with piercing eyes that reflect both wisdom and battle-hardened experience. His physique shows the perfect balance of a trained warrior and a scholarly mage. + +## Uniform and Attire +Kris wears the distinguished uniform of the Capital Mages Guild, reflecting his high status and combat role: + +- **Primary Garment**: A flowing dark navy blue cape with ornate silver trim and decorative patterns along the edges +- **Chest Armor**: Black studded leather chest piece with metallic reinforcements, providing protection while maintaining mobility for spellcasting +- **Under-Layer**: Dark practical tunic suitable for both combat and magical work +- **Belt and Accessories**: Wide leather belt with pouches for spell components and magical implements +- **Overall Style**: [Setting:clothing/battle-mage-uniform] - a perfect blend of martial protection and mage regalia, designed for a high-ranking guild battle mage + +The uniform demonstrates his dual nature as both a formidable warrior and a powerful spellcaster, with the rich materials and craftsmanship befitting his status in the guild hierarchy. + +## Abilities and Skills +- **Combat Mastery**: Expert in various types of knightly weapons +- **Magical Prowess**: First-class battle mage with fantastic combat magical abilities +- **Battle Intuition**: Possesses a special "battle mage intuition" that alerts him to surrounding dangers and dark magic +- **Quick Thinking**: Incredible wit and strategic thinking in combat situations + +## Weapons and Equipment +- [Item:battle-mage-staff] (primary magical focus) +- [Item:guild-ceremonial-blade] (backup weapon) +- Various knightly weapons mastered through training + +## Major Accomplishments + +### The Undead Invasion +Kris stopped an invasion by [Character:black-mage] when zombies, skeletons, and giant skeleton spiders began emerging from the swamp near the village of [Location:tri-peskary] (named after its tavern). The villagers couldn't mount proper resistance or call for help as no one believed them, but Kris happened to be nearby and saved his world from the invasion. + +### Resistance Against the Supreme Mage +Kris, along with his friends and other mages who joined him, offered resistance and defiance against [Character:supreme-mage] who planned to cause an armageddon and wipe the entire village and swamp from the face of the earth. To stop the armageddon created by the Supreme Mage, Kris and his friends slowed time, created a cocoon around the armageddon, carefully lowered it to the lake surface, and hid it by creating a grassy field above. However, this only slowed the process but didn't stop the problem, which future generations would have to solve. + +### The Skeleton Queen Campaign +In his next adventure, Kris traveled to fight [Creature:skeleton-queen] in a remote region of his kingdom. He discovered that the Skeleton Queen was actually [Character:lady-tamara] - heir to a castle who was exiled and cast out by [Character:lord-venedikt], who was the best friend and advisor to [Character:supreme-mage]. + +## Relationships +- **Grandson**: [Character:camelot] (main timeline hero) +- **Allies**: Fellow guild mages and resistance fighters +- **Enemies**: [Character:black-mage], [Character:supreme-mage], [Character:lord-venedikt] +- **Redeemed Enemy**: [Character:lady-tamara] (formerly [Creature:skeleton-queen]) + +## Location Associations +- **Home Base**: [City:grenoble] in [World:camelot-world] +- **Mission Areas**: [Location:tri-peskary], remote kingdom regions +- **Time Period**: [Location:kris-era] - events occurring long before the main storyline + +## Legacy +Kris's actions during his time set the foundation for the world that his grandson Camelot would later inherit. His containment of the Supreme Mage's armageddon created a problem that would echo through generations, while his heroic deeds established him as a legendary figure in the guild's history. \ No newline at end of file diff --git a/heroes/kris/photos/kriss.png b/heroes/kris/photos/kriss.png new file mode 100644 index 0000000..bfeb96e Binary files /dev/null and b/heroes/kris/photos/kriss.png differ diff --git a/heroes/lady-tamara/description.md b/heroes/lady-tamara/description.md new file mode 100644 index 0000000..7dc24b1 --- /dev/null +++ b/heroes/lady-tamara/description.md @@ -0,0 +1,12 @@ +# Lady Tamara - The Transformed Heir + +## Basic Information +- **True Identity**: Castle heir, formerly known as [Creature:skeleton-queen] +- **World**: [World:camelot-world] during [Location:kris-era] +- **Exiled by**: [Character:lord-venedikt] +- **Encountered by**: [Character:kris] + +## Overview +Originally the rightful heir to a castle, Lady Tamara was exiled and cast out by [Character:lord-venedikt]. Through dark circumstances, she became the [Creature:skeleton-queen] that [Character:kris] was sent to fight. Upon meeting her, Kris discovered her true identity and tragic story. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/heroes/lord-venedikt/description.md b/heroes/lord-venedikt/description.md new file mode 100644 index 0000000..cf4c5bd --- /dev/null +++ b/heroes/lord-venedikt/description.md @@ -0,0 +1,12 @@ +# Lord Venedikt - The Advisor + +## Basic Information +- **Title**: Lord and Advisor +- **World**: [World:camelot-world] during [Location:kris-era] +- **Relationship**: Best friend and advisor to [Character:supreme-mage] +- **Actions**: Exiled [Character:lady-tamara] from her rightful castle + +## Overview +A powerful lord who served as the best friend and trusted advisor to the [Character:supreme-mage]. Responsible for exiling [Character:lady-tamara] from her castle inheritance, setting in motion the events that led to her transformation into the [Creature:skeleton-queen]. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/heroes/nataly/description.md b/heroes/nataly/description.md new file mode 100644 index 0000000..51c28c7 --- /dev/null +++ b/heroes/nataly/description.md @@ -0,0 +1,47 @@ +# Nataly - Character Description + +## Basic Information +- **Full Name**: Nataly +- **Age**: 44 years old +- **Gender**: Female +- **Role**: Scientist chemist, Vanechka's mother +- **World Origin**: [World:modern-world] +- **Residence**: [City:gronin] + +## Physical Appearance +- **Age Group**: Middle-aged adult (44 years) +- **Gender**: Female +- **Profession**: Research scientist and chemist +- **Background**: Modern professional woman + +## Professional Life +- **Occupation**: Scientist chemist +- **Workplace**: Laboratory in [City:gronin] +- **Specialization**: Chemical research and analysis +- **Experience**: Established career in scientific research + +## Family and Personal Life +- **Children**: Vanechka (mother of) +- **Family Role**: Primary caregiver and working mother +- **Work-Life Balance**: Balancing scientific career with parenting responsibilities +- **Living Situation**: Urban life in modern city environment + +## Cross-References +- **Home City**: [City:gronin] - modern contemporary city +- **Workplace**: Laboratory facilities in [City:gronin] +- **World**: [World:modern-world] - contemporary Earth-like reality +- **Children**: Vanechka (son, referenced in description) + +## Professional Environment +- **Laboratory Work**: Modern research facility environment +- **Scientific Community**: Part of contemporary research establishment +- **Technology Access**: Modern scientific equipment and methodology +- **Career Development**: Established professional in chemical sciences + +## Subdirectories +- `photos/` - Character portraits and scenes +- `prompts/` - Character-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/nick/description.md b/heroes/nick/description.md new file mode 100644 index 0000000..0b51c93 --- /dev/null +++ b/heroes/nick/description.md @@ -0,0 +1,18 @@ +# Nick - Character Description + +## Basic Information +- **Full Name**: Nick +- **Age**: 14 years old +- **Gender**: Boy +- **Role**: Young adventurer + +## Physical Appearance +- **Age Group**: Young teenager +- **Gender**: Male + +## Cross-References +- **Associates**: [Character:dan], [Character:tim] + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/heroes/supreme-mage/description.md b/heroes/supreme-mage/description.md new file mode 100644 index 0000000..be29fd4 --- /dev/null +++ b/heroes/supreme-mage/description.md @@ -0,0 +1,12 @@ +# Supreme Mage - The Armageddon Initiator + +## Basic Information +- **Title**: Supreme Mage of the Realm +- **World**: [World:camelot-world] during [Location:kris-era] +- **Ally**: [Character:lord-venedikt] (best friend and advisor) +- **Enemy of**: [Character:kris] + +## Overview +The highest-ranking mage who planned to cause an armageddon to destroy the village of [Location:tri-peskary] and its surrounding swamp to stop the undead emergence. His extreme solution was opposed by [Character:kris] and other mages. Kris contained the armageddon but only delayed it, leaving the problem for future generations. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/items/battle-mage-staff/description.md b/items/battle-mage-staff/description.md new file mode 100644 index 0000000..b59210f --- /dev/null +++ b/items/battle-mage-staff/description.md @@ -0,0 +1,21 @@ +# Battle Mage Staff - Kris's Primary Focus + +## Basic Information +- **Type**: Magical Staff/Combat Focus +- **Owner**: [Character:kris] +- **World**: [World:camelot-world] during [Location:kris-era] +- **Style**: [Setting:weapons/magical-weapons] + +## Overview +The primary magical implement wielded by [Character:kris] during his service as a Battle Mage of the Capital Guild. This staff serves both as a focus for his combat magic and as a symbol of his rank within the guild hierarchy. + +## Properties +- **Magical Focus**: Channels and amplifies battle magic +- **Combat Utility**: Can be used in physical combat when needed +- **Guild Authority**: Represents official rank and standing +- **Battle Intuition Enhancement**: May augment Kris's special battle mage intuition + +## Usage +Essential for Kris's magical abilities, particularly during major confrontations such as the undead invasion at [Location:tri-peskary] and his resistance against [Character:supreme-mage]'s armageddon. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/items/camelot-staff/description.md b/items/camelot-staff/description.md new file mode 100644 index 0000000..0190f35 --- /dev/null +++ b/items/camelot-staff/description.md @@ -0,0 +1,24 @@ +# Camelot Staff - Item Description + +## Basic Information +- **Item Name**: Camelot Staff +- **Type**: High mage staff with green crystal +- **Origin**: [World:camelot-world] +- **Material**: Magical wood with green crystal + +## Properties +- **Power Level**: High mage tier +- **Crystal Color**: Green +- **Magical Properties**: Enhanced spellcasting + +## Cross-References +- **Owner**: [Character:camelot] +- **World**: [World:camelot-world] + +## Subdirectories +- `images/` - Item visualizations +- `prompts/` - Item-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/items/guild-ceremonial-blade/description.md b/items/guild-ceremonial-blade/description.md new file mode 100644 index 0000000..b89e5b4 --- /dev/null +++ b/items/guild-ceremonial-blade/description.md @@ -0,0 +1,21 @@ +# Guild Ceremonial Blade - Backup Weapon + +## Basic Information +- **Type**: Ceremonial Sword/Backup Weapon +- **Owner**: [Character:kris] +- **World**: [World:camelot-world] during [Location:kris-era] +- **Style**: [Setting:weapons/medieval-weapons] + +## Overview +A ceremonial blade carried by [Character:kris] as both a symbol of his guild rank and a practical backup weapon. Represents the dual nature of battle mages who must be skilled in both magical and physical combat. + +## Properties +- **Guild Symbolism**: Denotes rank within the Capital Mages Guild +- **Combat Ready**: Functional weapon despite ceremonial nature +- **Quality Craftsmanship**: Befitting a high-ranking guild member +- **Knightly Tradition**: Reflects Kris's mastery of knightly weapons + +## Usage +Serves as Kris's secondary weapon when his [Item:battle-mage-staff] is not suitable for close combat situations, demonstrating his comprehensive martial training. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/items/mystical-staff/description.md b/items/mystical-staff/description.md new file mode 100644 index 0000000..0cacbc6 --- /dev/null +++ b/items/mystical-staff/description.md @@ -0,0 +1,25 @@ +# Mystical Staff - Item Description + +## Basic Information +- **Item Name**: Mystical Staff +- **Type**: Ultimate magical staff +- **Appearance**: Straight, black, polished, no decorations or ornaments +- **Material**: Unknown mystical material + +## Properties +- **Power Level**: Maximum power +- **Design**: Minimalist, no decorative elements +- **Color**: Pure black, polished finish +- **Shape**: Perfectly straight + +## Special Features +- **Power**: Possesses maximum magical strength +- **Simplicity**: Power through minimalism, not ornamentation + +## Subdirectories +- `images/` - Item visualizations +- `prompts/` - Item-specific prompts + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/abandoned-building/description.md b/locations/abandoned-building/description.md new file mode 100644 index 0000000..edf59ac --- /dev/null +++ b/locations/abandoned-building/description.md @@ -0,0 +1,23 @@ +# Abandoned Building - Location Description + +## Basic Information +- **Location Name**: Abandoned Building +- **Type**: Ruined structure +- **World**: Fantasy realm +- **Setting**: Old, forgotten building + +## Visual Style +- **Architecture**: Decaying, ruined building +- **Atmosphere**: Mysterious, dusty, forgotten +- **Condition**: Abandoned and deteriorating + +## Cross-References +- **Items Found**: [Item:dusty-sword], [Item:dusty-armor] + +## Subdirectories +- `images/` - Generated location images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/abandoned-building/images/road-to-toward-city.jpeg b/locations/abandoned-building/images/road-to-toward-city.jpeg new file mode 100644 index 0000000..b2919f0 Binary files /dev/null and b/locations/abandoned-building/images/road-to-toward-city.jpeg differ diff --git a/locations/academy-town-geneva/description.md b/locations/academy-town-geneva/description.md new file mode 100644 index 0000000..db429c8 --- /dev/null +++ b/locations/academy-town-geneva/description.md @@ -0,0 +1,23 @@ +# Academy Town Geneva - Location Description + +## Basic Information +- **Location Name**: Academy Town Geneva +- **Type**: Academic district +- **World**: [World:modern-world] +- **Setting**: University and research area in Geneva + +## Visual Style +- **Architecture**: Academic buildings and campus +- **Atmosphere**: Educational and scholarly environment +- **Features**: University facilities and student areas + +## Cross-References +- **Students**: [Character:edd] + +## Subdirectories +- `images/` - Generated location images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/guardian-library/description.md b/locations/guardian-library/description.md new file mode 100644 index 0000000..e021957 --- /dev/null +++ b/locations/guardian-library/description.md @@ -0,0 +1,23 @@ +# Guardian Library - Location Description + +## Basic Information +- **Location Name**: Guardian Library +- **Type**: Magical library +- **World**: Fantasy realm +- **Setting**: Ancient repository of knowledge + +## Visual Style +- **Architecture**: Mystical library with towering bookshelves +- **Atmosphere**: Ancient wisdom and magical knowledge +- **Guardians**: Protected by magical guardians + +## Cross-References +- **Guardian**: [Character:library-guardian] + +## Subdirectories +- `images/` - Generated location images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/kris-era/description.md b/locations/kris-era/description.md new file mode 100644 index 0000000..44ddeee --- /dev/null +++ b/locations/kris-era/description.md @@ -0,0 +1,20 @@ +# Kris Era - The Age of the Battle Mage + +## Basic Information +- **Type**: Historical Time Period +- **World**: [World:camelot-world] +- **Main Hero**: [Character:kris] +- **Relationship to Main Timeline**: Occurs long before [Character:camelot]'s story + +## Overview +A significant historical period in [World:camelot-world] when [Character:kris], grandfather of [Character:camelot], served as a Battle Mage of the Capital Guild in [City:grenoble]. This era was marked by supernatural threats, political intrigue, and magical conflicts that would shape the world for generations to come. + +## Major Events +- **The Undead Invasion**: [Character:black-mage]'s assault on [Location:tri-peskary] +- **The Armageddon Crisis**: [Character:supreme-mage]'s extreme solution and [Character:kris]'s containment +- **The Skeleton Queen Campaign**: Discovery of [Character:lady-tamara]'s true identity + +## Legacy +The actions and decisions made during this era, particularly Kris's containment of the Supreme Mage's armageddon, created ongoing problems that future generations, including [Character:camelot], would need to address. + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/locations/quantum-lab-geneva/description.md b/locations/quantum-lab-geneva/description.md new file mode 100644 index 0000000..4ba8c8f --- /dev/null +++ b/locations/quantum-lab-geneva/description.md @@ -0,0 +1,24 @@ +# Quantum Laboratory Geneva - Location Description + +## Basic Information +- **Location Name**: Quantum Laboratory Geneva +- **Type**: Modern scientific laboratory +- **World**: [World:modern-world] +- **Setting**: Advanced physics research facility in Geneva + +## Visual Style +- **Architecture**: Modern laboratory building +- **Equipment**: Advanced quantum physics equipment +- **Atmosphere**: High-tech scientific environment + +## Cross-References +- **Director**: [Character:konstantin] +- **Students**: [Character:edd] + +## Subdirectories +- `images/` - Generated location images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/source-castle/description.md b/locations/source-castle/description.md new file mode 100644 index 0000000..a0b36f0 --- /dev/null +++ b/locations/source-castle/description.md @@ -0,0 +1,20 @@ +# Source Castle - Location Description + +## Basic Information +- **Location Name**: Source Castle +- **Type**: Magical castle +- **World**: Fantasy realm +- **Setting**: Ancient magical fortress + +## Visual Style +- **Architecture**: Medieval fantasy castle +- **Atmosphere**: Mystical and ancient +- **Special Features**: Magical source or fountain + +## Subdirectories +- `images/` - Generated location images +- `prompts/` - Successful prompts archive + +--- +*Last Updated: [Date]* +*Consistency Level: STANDARD* \ No newline at end of file diff --git a/locations/tri-peskary/description.md b/locations/tri-peskary/description.md new file mode 100644 index 0000000..0e65299 --- /dev/null +++ b/locations/tri-peskary/description.md @@ -0,0 +1,16 @@ +# Tri Peskary - The Village by the Cursed Swamp + +## Basic Information +- **Type**: Village +- **World**: [World:camelot-world] during [Location:kris-era] +- **Notable Feature**: Tavern with the same name as the village +- **Threat**: Undead emergence from nearby swamp + +## Overview +A small village known for its tavern called "Tri Peskary" (Three Minnows). The village became the center of an undead invasion when [Character:black-mage] caused zombies, skeletons, and giant skeleton spiders to emerge from the nearby swamp. The villagers were unable to defend themselves or call for help as no one believed their reports of the supernatural threat. The village was saved by [Character:kris] who happened to be in the area. + +## Locations +- **Tri Peskary Tavern**: The village's main gathering place and namesake +- **The Cursed Swamp**: Source of the undead invasion, located near the village + +*[Placeholder - needs detailed expansion]* \ No newline at end of file diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 100755 index 0000000..455129a --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1,21 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/bin/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules" +else + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/bin/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules:$NODE_PATH" +fi +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../.pnpm/typescript@5.9.2/node_modules/typescript/bin/tsc" "$@" +else + exec node "$basedir/../.pnpm/typescript@5.9.2/node_modules/typescript/bin/tsc" "$@" +fi diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 100755 index 0000000..eed20bc --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1,21 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/bin/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules" +else + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/bin/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules/typescript/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/typescript@5.9.2/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules:$NODE_PATH" +fi +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../.pnpm/typescript@5.9.2/node_modules/typescript/bin/tsserver" "$@" +else + exec node "$basedir/../.pnpm/typescript@5.9.2/node_modules/typescript/bin/tsserver" "$@" +fi diff --git a/node_modules/.bin/tsx b/node_modules/.bin/tsx new file mode 100755 index 0000000..a2b1425 --- /dev/null +++ b/node_modules/.bin/tsx @@ -0,0 +1,21 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules/tsx/dist/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules/tsx/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules" +else + export NODE_PATH="/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules/tsx/dist/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules/tsx/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/tsx@4.20.5/node_modules:/projects/my-projects/Magic-Building/node_modules/.pnpm/node_modules:$NODE_PATH" +fi +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../.pnpm/tsx@4.20.5/node_modules/tsx/dist/cli.mjs" "$@" +else + exec node "$basedir/../.pnpm/tsx@4.20.5/node_modules/tsx/dist/cli.mjs" "$@" +fi diff --git a/node_modules/.modules.yaml b/node_modules/.modules.yaml new file mode 100644 index 0000000..3b7732f --- /dev/null +++ b/node_modules/.modules.yaml @@ -0,0 +1,159 @@ +hoistPattern: + - '*' +hoistedDependencies: + '@esbuild/aix-ppc64@0.25.9': + '@esbuild/aix-ppc64': private + '@esbuild/android-arm64@0.25.9': + '@esbuild/android-arm64': private + '@esbuild/android-arm@0.25.9': + '@esbuild/android-arm': private + '@esbuild/android-x64@0.25.9': + '@esbuild/android-x64': private + '@esbuild/darwin-arm64@0.25.9': + '@esbuild/darwin-arm64': private + '@esbuild/darwin-x64@0.25.9': + '@esbuild/darwin-x64': private + '@esbuild/freebsd-arm64@0.25.9': + '@esbuild/freebsd-arm64': private + '@esbuild/freebsd-x64@0.25.9': + '@esbuild/freebsd-x64': private + '@esbuild/linux-arm64@0.25.9': + '@esbuild/linux-arm64': private + '@esbuild/linux-arm@0.25.9': + '@esbuild/linux-arm': private + '@esbuild/linux-ia32@0.25.9': + '@esbuild/linux-ia32': private + '@esbuild/linux-loong64@0.25.9': + '@esbuild/linux-loong64': private + '@esbuild/linux-mips64el@0.25.9': + '@esbuild/linux-mips64el': private + '@esbuild/linux-ppc64@0.25.9': + '@esbuild/linux-ppc64': private + '@esbuild/linux-riscv64@0.25.9': + '@esbuild/linux-riscv64': private + '@esbuild/linux-s390x@0.25.9': + '@esbuild/linux-s390x': private + '@esbuild/linux-x64@0.25.9': + '@esbuild/linux-x64': private + '@esbuild/netbsd-arm64@0.25.9': + '@esbuild/netbsd-arm64': private + '@esbuild/netbsd-x64@0.25.9': + '@esbuild/netbsd-x64': private + '@esbuild/openbsd-arm64@0.25.9': + '@esbuild/openbsd-arm64': private + '@esbuild/openbsd-x64@0.25.9': + '@esbuild/openbsd-x64': private + '@esbuild/openharmony-arm64@0.25.9': + '@esbuild/openharmony-arm64': private + '@esbuild/sunos-x64@0.25.9': + '@esbuild/sunos-x64': private + '@esbuild/win32-arm64@0.25.9': + '@esbuild/win32-arm64': private + '@esbuild/win32-ia32@0.25.9': + '@esbuild/win32-ia32': private + '@esbuild/win32-x64@0.25.9': + '@esbuild/win32-x64': private + agent-base@7.1.4: + agent-base: private + base64-js@1.5.1: + base64-js: private + bignumber.js@9.3.1: + bignumber.js: private + buffer-equal-constant-time@1.0.1: + buffer-equal-constant-time: private + debug@4.4.1: + debug: private + ecdsa-sig-formatter@1.0.11: + ecdsa-sig-formatter: private + esbuild@0.25.9: + esbuild: private + extend@3.0.2: + extend: private + fsevents@2.3.3: + fsevents: private + gaxios@6.7.1: + gaxios: private + gcp-metadata@6.1.1: + gcp-metadata: private + get-tsconfig@4.10.1: + get-tsconfig: private + google-auth-library@9.15.1: + google-auth-library: private + google-logging-utils@0.0.2: + google-logging-utils: private + gtoken@7.1.0: + gtoken: private + https-proxy-agent@7.0.6: + https-proxy-agent: private + is-stream@2.0.1: + is-stream: private + json-bigint@1.0.0: + json-bigint: private + jwa@2.0.1: + jwa: private + jws@4.0.0: + jws: private + ms@2.1.3: + ms: private + node-fetch@2.7.0: + node-fetch: private + resolve-pkg-maps@1.0.0: + resolve-pkg-maps: private + safe-buffer@5.2.1: + safe-buffer: private + tr46@0.0.3: + tr46: private + undici-types@7.10.0: + undici-types: private + uuid@9.0.1: + uuid: private + webidl-conversions@3.0.1: + webidl-conversions: private + whatwg-url@5.0.0: + whatwg-url: private + ws@8.18.3: + ws: private +included: + dependencies: true + devDependencies: true + optionalDependencies: true +injectedDeps: {} +layoutVersion: 5 +nodeLinker: isolated +packageManager: pnpm@10.11.0 +pendingBuilds: [] +prunedAt: Mon, 08 Sep 2025 15:39:10 GMT +publicHoistPattern: [] +registries: + '@jsr': https://npm.jsr.io/ + default: https://registry.npmjs.org/ +skipped: + - '@esbuild/aix-ppc64@0.25.9' + - '@esbuild/android-arm64@0.25.9' + - '@esbuild/android-arm@0.25.9' + - '@esbuild/android-x64@0.25.9' + - '@esbuild/darwin-arm64@0.25.9' + - '@esbuild/darwin-x64@0.25.9' + - '@esbuild/freebsd-arm64@0.25.9' + - '@esbuild/freebsd-x64@0.25.9' + - '@esbuild/linux-arm64@0.25.9' + - '@esbuild/linux-arm@0.25.9' + - '@esbuild/linux-ia32@0.25.9' + - '@esbuild/linux-loong64@0.25.9' + - '@esbuild/linux-mips64el@0.25.9' + - '@esbuild/linux-ppc64@0.25.9' + - '@esbuild/linux-riscv64@0.25.9' + - '@esbuild/linux-s390x@0.25.9' + - '@esbuild/netbsd-arm64@0.25.9' + - '@esbuild/netbsd-x64@0.25.9' + - '@esbuild/openbsd-arm64@0.25.9' + - '@esbuild/openbsd-x64@0.25.9' + - '@esbuild/openharmony-arm64@0.25.9' + - '@esbuild/sunos-x64@0.25.9' + - '@esbuild/win32-arm64@0.25.9' + - '@esbuild/win32-ia32@0.25.9' + - '@esbuild/win32-x64@0.25.9' + - fsevents@2.3.3 +storeDir: /projects/.pnpm-store/v10 +virtualStoreDir: .pnpm +virtualStoreDirMaxLength: 120 diff --git a/node_modules/.pnpm-workspace-state.json b/node_modules/.pnpm-workspace-state.json new file mode 100644 index 0000000..a3971e4 --- /dev/null +++ b/node_modules/.pnpm-workspace-state.json @@ -0,0 +1,25 @@ +{ + "lastValidatedTimestamp": 1757347442246, + "projects": {}, + "pnpmfileExists": false, + "settings": { + "autoInstallPeers": true, + "dedupeDirectDeps": false, + "dedupeInjectedDeps": true, + "dedupePeerDependents": true, + "dev": true, + "excludeLinksFromLockfile": false, + "hoistPattern": [ + "*" + ], + "hoistWorkspacePackages": true, + "injectWorkspacePackages": false, + "linkWorkspacePackages": false, + "nodeLinker": "isolated", + "optional": true, + "preferWorkspacePackages": false, + "production": true, + "publicHoistPattern": [] + }, + "filteredInstall": false +} diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/LICENSE.md b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +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. diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/README.md b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/README.md new file mode 100644 index 0000000..f739070 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/README.md @@ -0,0 +1,289 @@ +# Source Map Support + +[![NPM version](https://img.shields.io/npm/v/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![NPM downloads](https://img.shields.io/npm/dm/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support) +[![Build status](https://img.shields.io/github/workflow/status/cspotcode/node-source-map-support/Continuous%20Integration)](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install @cspotcode/source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r @cspotcode/source-map-support/register compiled.js +# Or to enable hookRequire +node -r @cspotcode/source-map-support/register-hook-require compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('@cspotcode/source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import '@cspotcode/source-map-support/register' + +// Instead of: +import sourceMapSupport from '@cspotcode/source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require @cspotcode/source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('@cspotcode/source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('@cspotcode/source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('@cspotcode/source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('@cspotcode/source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('@cspotcode/source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('@cspotcode/source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('@cspotcode/source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install @cspotcode/source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/browser-source-map-support.js b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0=12" + }, + "volta": { + "node": "16.11.0", + "npm": "7.24.2" + } +} diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts new file mode 100755 index 0000000..a787e69 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register-hook-require' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install({hookRequire: true}) diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.js b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.js new file mode 100644 index 0000000..6bc12ab --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register-hook-require.js @@ -0,0 +1,3 @@ +require('./').install({ + hookRequire: true +}); diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.d.ts b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.d.ts new file mode 100755 index 0000000..063cd7c --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.d.ts @@ -0,0 +1,7 @@ +// tslint:disable:no-useless-files + +// For following usage: +// import '@cspotcode/source-map-support/register' +// Instead of: +// import sourceMapSupport from '@cspotcode/source-map-support' +// sourceMapSupport.install() diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.js b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.js new file mode 100644 index 0000000..4f68e67 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/register.js @@ -0,0 +1 @@ +require('./').install(); diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.d.ts b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.d.ts new file mode 100755 index 0000000..d8cb9d8 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.d.ts @@ -0,0 +1,76 @@ +// Type definitions for source-map-support 0.5 +// Project: https://github.com/evanw/node-source-map-support +// Definitions by: Bart van der Schoor +// Jason Cheatham +// Alcedo Nathaniel De Guzman Jr +// Griffin Yourick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface RawSourceMap { + version: 3; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; +} + +/** + * Output of retrieveSourceMap(). + * From source-map-support: + * The map field may be either a string or the parsed JSON object (i.e., + * it must be a valid argument to the SourceMapConsumer constructor). + */ +export interface UrlAndMap { + url: string; + map: string | RawSourceMap; +} + +/** + * Options to install(). + */ +export interface Options { + handleUncaughtExceptions?: boolean | undefined; + hookRequire?: boolean | undefined; + emptyCacheBetweenOperations?: boolean | undefined; + environment?: 'auto' | 'browser' | 'node' | undefined; + overrideRetrieveFile?: boolean | undefined; + overrideRetrieveSourceMap?: boolean | undefined; + retrieveFile?(path: string): string; + retrieveSourceMap?(source: string): UrlAndMap | null; + /** + * Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support` + */ + redirectConflictingLibrary?: boolean; + /** + * Callback will be called every time we redirect due to `redirectConflictingLibrary` + * This allows consumers to log helpful warnings if they choose. + * @param parent NodeJS.Module which made the require() or require.resolve() call + * @param options options object internally passed to node's `_resolveFilename` hook + */ + onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void; +} + +export interface Position { + source: string; + line: number; + column: number; +} + +export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; +export function getErrorSource(error: Error): string | null; +export function mapSourcePosition(position: Position): Position; +export function retrieveSourceMap(source: string): UrlAndMap | null; +export function resetRetrieveHandlers(): void; + +/** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ +export function install(options?: Options): void; + +/** + * Uninstall SourceMap support. + */ +export function uninstall(): void; diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.js b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.js new file mode 100644 index 0000000..ad830b6 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@cspotcode/source-map-support/source-map-support.js @@ -0,0 +1,938 @@ +const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping'); +var path = require('path'); +const { fileURLToPath, pathToFileURL } = require('url'); +var util = require('util'); + +var fs; +try { + fs = require('fs'); + if (!fs.existsSync || !fs.readFileSync) { + // fs doesn't have all methods we need + fs = null; + } +} catch (err) { + /* nop */ +} + +/** + * Requires a module which is protected against bundler minification. + * + * @param {NodeModule} mod + * @param {string} request + */ +function dynamicRequire(mod, request) { + return mod.require(request); +} + +/** + * @typedef {{ + * enabled: boolean; + * originalValue: any; + * installedValue: any; + * }} HookState + * Used for installing and uninstalling hooks + */ + +// Increment this if the format of sharedData changes in a breaking way. +var sharedDataVersion = 1; + +/** + * @template T + * @param {T} defaults + * @returns {T} + */ +function initializeSharedData(defaults) { + var sharedDataKey = 'source-map-support/sharedData'; + if (typeof Symbol !== 'undefined') { + sharedDataKey = Symbol.for(sharedDataKey); + } + var sharedData = this[sharedDataKey]; + if (!sharedData) { + sharedData = { version: sharedDataVersion }; + if (Object.defineProperty) { + Object.defineProperty(this, sharedDataKey, { value: sharedData }); + } else { + this[sharedDataKey] = sharedData; + } + } + if (sharedDataVersion !== sharedData.version) { + throw new Error("Multiple incompatible instances of source-map-support were loaded"); + } + for (var key in defaults) { + if (!(key in sharedData)) { + sharedData[key] = defaults[key]; + } + } + return sharedData; +} + +// If multiple instances of source-map-support are loaded into the same +// context, they shouldn't overwrite each other. By storing handlers, caches, +// and other state on a shared object, different instances of +// source-map-support can work together in a limited way. This does require +// that future versions of source-map-support continue to support the fields on +// this object. If this internal contract ever needs to be broken, increment +// sharedDataVersion. (This version number is not the same as any of the +// package's version numbers, which should reflect the *external* API of +// source-map-support.) +var sharedData = initializeSharedData({ + + // Only install once if called multiple times + // Remember how the environment looked before installation so we can restore if able + /** @type {HookState} */ + errorPrepareStackTraceHook: undefined, + /** @type {HookState} */ + processEmitHook: undefined, + /** @type {HookState} */ + moduleResolveFilenameHook: undefined, + + /** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */ + onConflictingLibraryRedirectArr: [], + + // If true, the caches are reset before a stack trace formatting operation + emptyCacheBetweenOperations: false, + + // Maps a file path to a string containing the file contents + fileContentsCache: Object.create(null), + + // Maps a file path to a source map for that file + /** @type {Record C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + const key = getCacheKey(path); + if(hasFileContentsCacheFromKey(key)) { + return getFileContentsCacheFromKey(key); + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return setFileContentsCache(path, contents); +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if(!file) return url; + // given that this happens within error formatting codepath, probably best to + // fallback instead of throwing if anything goes wrong + try { + // if should output a URL + if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) { + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return new URL(url, file).toString(); + } + if(path.isAbsolute(url)) { + return new URL(pathToFileURL(url), file).toString(); + } + // url is relative path or URL + return new URL(url.replace(/\\/g, '/'), file).toString(); + } + // if should output a path (unless URL is something like https://) + if(path.isAbsolute(file)) { + if(isFileUrl(url)) { + return fileURLToPath(url); + } + if(isSchemeRelativeUrl(url)) { + return fileURLToPath(new URL(url, 'file://')); + } + if(isAbsoluteUrl(url)) { + // url is a non-file URL + // Go with the URL + return url; + } + if(path.isAbsolute(url)) { + // Normalize at all? decodeURI or normalize slashes? + return path.normalize(url); + } + // url is relative path or URL + return path.join(file, '..', decodeURI(url)); + } + // If we get here, file is relative. + // Shouldn't happen since node identifies modules with absolute paths or URLs. + // But we can take a stab at returning something meaningful anyway. + if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) { + return url; + } + return path.join(file, '..', url); + } catch(e) { + return url; + } +} + +// Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path +function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) { + try { + if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl; + if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString(); + } else if(path.isAbsolute(matchStyleOf)) { + if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) { + return fileURLToPath(new URL(pathOrUrl, 'file://')); + } + } + return pathOrUrl; + } catch(e) { + return pathOrUrl; + } +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(tryFileURLToPath(source)); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +/** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */ +var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers); +sharedData.internalRetrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = Buffer.from(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL)); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = getSourceMapCache(position.source); + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = setSourceMapCache(position.source, { + url: urlAndMap.url, + map: new AnyMap(urlAndMap.map, urlAndMap.url) + }); + + // Overwrite trace-mapping's resolutions, because they do not handle + // Windows paths the way we want. + // TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping? + sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s)); + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + setFileContentsCache(resolvedSource, contents); + } + }); + } + } else { + sourceMap = setSourceMapCache(position.source, { + url: null, + map: null + }); + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map) { + var originalPosition = originalPositionFor(sourceMap.map, position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + // originalPosition.source has *already* been resolved against sourceMap.url + // so is *already* as absolute as possible. + // However, we want to ensure we output in same format as input: URL or native path + originalPosition.source = matchStyleOfPathOrUrl( + position.source, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +// Update 2022-04-29: +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804 +// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750 +// The implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var isAsync = this.isAsync ? this.isAsync() : false; + if(isAsync) { + line += 'async '; + var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false; + var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false; + if(isPromiseAny || isPromiseAll) { + line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index '; + var promiseIndex = this.getPromiseIndex(); + line += promiseIndex + ')'; + } + } + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + // v8 does not expose its internal isWasm, etc methods, so we do this instead. + if(source.startsWith('wasm://')) { + state.curPosition = null; + return frame; + } + + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(process.version) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +var kIsNodeError = undefined; +try { + // Get a deliberate ERR_INVALID_ARG_TYPE + // TODO is there a better way to reliably get an instance of NodeError? + path.resolve(123); +} catch(e) { + const symbols = Object.getOwnPropertySymbols(e); + const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0}); + if(symbol) kIsNodeError = symbol; +} + +const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err); + +/** @param {HookState} hookState */ +function createPrepareStackTrace(hookState) { + return prepareStackTrace; + + // This function is part of the V8 stack trace API, for more info see: + // https://v8.dev/docs/stack-trace-api + function prepareStackTrace(error, stack) { + if(!hookState.enabled) return hookState.originalValue.apply(this, arguments); + + if (sharedData.emptyCacheBetweenOperations) { + clearCaches(); + } + + // node gives its own errors special treatment. Mimic that behavior + // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128 + // https://github.com/nodejs/node/pull/39182 + var errorString; + if (kIsNodeError) { + if(kIsNodeError in error) { + errorString = `${error.name} [${error.code}]: ${error.message}`; + } else { + errorString = ErrorPrototypeToString(error); + } + } else { + var name = error.name || 'Error'; + var message = error.message || ''; + errorString = message ? name + ": " + message : name; + } + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); + } +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = getFileContentsCache(source); + + const sourceAsPath = tryFileURLToPath(source); + + // Support files on disk + if (!contents && fs && fs.existsSync(sourceAsPath)) { + try { + contents = fs.readFileSync(sourceAsPath, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printFatalErrorUponExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + if (process.stderr._handle && process.stderr._handle.setBlocking) { + process.stderr._handle.setBlocking(true); + } + + if (source) { + console.error(source); + } + + // Matches node's behavior for colorized output + console.error( + util.inspect(error, { + customInspect: false, + colors: process.stderr.isTTY + }) + ); +} + +function shimEmitUncaughtException () { + const originalValue = process.emit; + var hook = sharedData.processEmitHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + var isTerminatingDueToFatalException = false; + var fatalException; + + process.emit = sharedData.processEmitHook.installedValue = function (type) { + const hadListeners = originalValue.apply(this, arguments); + if(hook.enabled) { + if (type === 'uncaughtException' && !hadListeners) { + isTerminatingDueToFatalException = true; + fatalException = arguments[1]; + process.exit(1); + } + if (type === 'exit' && isTerminatingDueToFatalException) { + printFatalErrorUponExit(fatalException); + } + } + return hadListeners; + }; +} + +var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + + // Redirect subsequent imports of "source-map-support" + // to this package + const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options; + if(redirectConflictingLibrary) { + if (!sharedData.moduleResolveFilenameHook) { + const originalValue = Module._resolveFilename; + const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = { + enabled: true, + originalValue, + installedValue: undefined, + } + Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) { + if (moduleResolveFilenameHook.enabled) { + // Match all source-map-support entrypoints: source-map-support, source-map-support/register + let requestRedirect; + if (request === 'source-map-support') { + requestRedirect = './'; + } else if (request === 'source-map-support/register') { + requestRedirect = './register'; + } + + if (requestRedirect !== undefined) { + const newRequest = require.resolve(requestRedirect); + for (const cb of sharedData.onConflictingLibraryRedirectArr) { + cb(request, parent, isMain, options, newRequest); + } + request = newRequest; + } + } + + return originalValue.call(this, request, parent, isMain, options); + } + } + if (onConflictingLibraryRedirect) { + sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect); + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + sharedData.retrieveFileHandlers.length = 0; + } + + sharedData.retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + sharedData.retrieveMapHandlers.length = 0; + } + + sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + setFileContentsCache(filename, content); + setSourceMapCache(filename, undefined); + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!sharedData.emptyCacheBetweenOperations) { + sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + + // Install the error reformatter + if (!sharedData.errorPrepareStackTraceHook) { + const originalValue = Error.prepareStackTrace; + sharedData.errorPrepareStackTraceHook = { + enabled: true, + originalValue, + installedValue: undefined + }; + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook); + } + + if (!sharedData.processEmitHook) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + shimEmitUncaughtException(); + } + } +}; + +exports.uninstall = function() { + if(sharedData.processEmitHook) { + // Disable behavior + sharedData.processEmitHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + if(process.emit === sharedData.processEmitHook.installedValue) { + process.emit = sharedData.processEmitHook.originalValue; + } + sharedData.processEmitHook = undefined; + } + if(sharedData.errorPrepareStackTraceHook) { + // Disable behavior + sharedData.errorPrepareStackTraceHook.enabled = false; + // If possible or necessary, remove our hook function. + // In vanilla environments, prepareStackTrace is `undefined`. + // We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function. + // If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both. + if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') { + Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue; + } + sharedData.errorPrepareStackTraceHook = undefined; + } + if (sharedData.moduleResolveFilenameHook) { + // Disable behavior + sharedData.moduleResolveFilenameHook.enabled = false; + // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us. + var Module = dynamicRequire(module, 'module'); + if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) { + Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue; + } + sharedData.moduleResolveFilenameHook = undefined; + } + sharedData.onConflictingLibraryRedirectArr.length = 0; +} + +exports.resetRetrieveHandlers = function() { + sharedData.retrieveFileHandlers.length = 0; + sharedData.retrieveMapHandlers.length = 0; +} diff --git a/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@jridgewell/trace-mapping b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@jridgewell/trace-mapping new file mode 120000 index 0000000..1190759 --- /dev/null +++ b/node_modules/.pnpm/@cspotcode+source-map-support@0.8.1/node_modules/@jridgewell/trace-mapping @@ -0,0 +1 @@ +../../../@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping \ No newline at end of file diff --git a/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/README.md b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/README.md new file mode 100644 index 0000000..b2f1930 --- /dev/null +++ b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/bin/esbuild b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/bin/esbuild new file mode 100755 index 0000000..6a456f3 Binary files /dev/null and b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/bin/esbuild differ diff --git a/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/package.json b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/package.json new file mode 100644 index 0000000..8d0ec96 --- /dev/null +++ b/node_modules/.pnpm/@esbuild+linux-x64@0.25.9/node_modules/@esbuild/linux-x64/package.json @@ -0,0 +1,20 @@ +{ + "name": "@esbuild/linux-x64", + "version": "0.25.9", + "description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=18" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/LICENSE b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/README.md b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/README.md new file mode 100644 index 0000000..7fb7457 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/README.md @@ -0,0 +1,377 @@ +# Google Gen AI SDK for TypeScript and JavaScript + +[![NPM Downloads](https://img.shields.io/npm/dw/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) +[![Node Current](https://img.shields.io/node/v/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) + +---------------------- +**Documentation:** https://googleapis.github.io/js-genai/ + +---------------------- + +The Google Gen AI JavaScript SDK is designed for +TypeScript and JavaScript developers to build applications powered by Gemini. The SDK +supports both the [Gemini Developer API](https://ai.google.dev/gemini-api/docs) +and [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview). + +The Google Gen AI SDK is designed to work with Gemini 2.0 features. + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +## Prerequisites + +1. Node.js version 20 or later + +### The following are required for Vertex AI users (excluding Vertex AI Studio) +1. [Select](https://console.cloud.google.com/project) or [create](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) a Google Cloud project. +1. [Enable billing for your project](https://cloud.google.com/billing/docs/how-to/modify-project). +1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). +1. [Configure authentication](https://cloud.google.com/docs/authentication) for your project. + * [Install the gcloud CLI](https://cloud.google.com/sdk/docs/install). + * [Initialize the gcloud CLI](https://cloud.google.com/sdk/docs/initializing). + * Create local authentication credentials for your user account: + + ```sh + gcloud auth application-default login + ``` +A list of accepted authentication options are listed in [GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/3ae120d0a45c95e36c59c9ac8286483938781f30/src/auth/googleauth.ts#L87) interface of google-auth-library-node.js GitHub repo. + +## Installation + +To install the SDK, run the following command: + +```shell +npm install @google/genai +``` + +## Quickstart + +The simplest way to get started is to use an API key from +[Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Why is the sky blue?', + }); + console.log(response.text); +} + +main(); +``` + +## Initialization + +The Google Gen AI SDK provides support for both the +[Google AI Studio](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) + implementations of the Gemini API. + +### Gemini Developer API + +For server-side applications, initialize using an API key, which can +be acquired from [Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +#### Browser + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +In the browser the initialization code is identical: + + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +### Vertex AI + +Sample code for VertexAI initialization: + +```typescript +import { GoogleGenAI } from '@google/genai'; + +const ai = new GoogleGenAI({ + vertexai: true, + project: 'your_project', + location: 'your_location', +}); +``` + +### (Optional) (NodeJS only) Using environment variables: + +For NodeJS environments, you can create a client by configuring the necessary +environment variables. Configuration setup instructions depends on whether +you're using the Gemini Developer API or the Gemini API in Vertex AI. + +**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: + +```bash +export GOOGLE_API_KEY='your-api-key' +``` + +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: + +```bash +export GOOGLE_GENAI_USE_VERTEXAI=true +export GOOGLE_CLOUD_PROJECT='your-project-id' +export GOOGLE_CLOUD_LOCATION='us-central1' +``` + +```typescript +import {GoogleGenAI} from '@google/genai'; + +const ai = new GoogleGenAI(); +``` + +## API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `apiVersion`. For example, to set the API version to +`v1` for Vertex AI: + +```typescript +const ai = new GoogleGenAI({ + vertexai: true, + project: 'your_project', + location: 'your_location', + apiVersion: 'v1' +}); +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```typescript +const ai = new GoogleGenAI({ + apiKey: 'GEMINI_API_KEY', + apiVersion: 'v1alpha' +}); +``` + +## GoogleGenAI overview + +All API features are accessed through an instance of the `GoogleGenAI` classes. +The submodules bundle together related API methods: + +- [`ai.models`](https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html): + Use `models` to query models (`generateContent`, `generateImages`, ...), or + examine their metadata. +- [`ai.caches`](https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html): + Create and manage `caches` to reduce costs when repeatedly using the same + large prompt prefix. +- [`ai.chats`](https://googleapis.github.io/js-genai/release_docs/classes/chats.Chats.html): + Create local stateful `chat` objects to simplify multi turn interactions. +- [`ai.files`](https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html): + Upload `files` to the API and reference them in your prompts. + This reduces bandwidth if you use a file many times, and handles files too + large to fit inline with your prompt. +- [`ai.live`](https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html): + Start a `live` session for real time interaction, allows text + audio + video + input, and text or audio output. + +## Samples + +More samples can be found in the +[github samples directory](https://github.com/googleapis/js-genai/tree/main/sdk-samples). + +### Streaming + +For quicker, more responsive API interactions use the `generateContentStream` +method which yields chunks as they're generated: + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContentStream({ + model: 'gemini-2.0-flash-001', + contents: 'Write a 100-word poem.', + }); + for await (const chunk of response) { + console.log(chunk.text); + } +} + +main(); +``` + +### Function Calling + +To let Gemini to interact with external systems, you can provide +`functionDeclaration` objects as `tools`. To use these tools it's a 4 step + +1. **Declare the function name, description, and parametersJsonSchema** +2. **Call `generateContent` with function calling enabled** +3. **Use the returned `FunctionCall` parameters to call your actual function** +3. **Send the result back to the model (with history, easier in `ai.chat`) + as a `FunctionResponse`** + +```typescript +import {GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +async function main() { + const controlLightDeclaration: FunctionDeclaration = { + name: 'controlLight', + parametersJsonSchema: { + type: 'object', + properties:{ + brightness: { + type:'number', + }, + colorTemperature: { + type:'string', + }, + }, + required: ['brightness', 'colorTemperature'], + }, + }; + + const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Dim the lights so the room feels cozy and warm.', + config: { + toolConfig: { + functionCallingConfig: { + // Force it to call any function + mode: FunctionCallingConfigMode.ANY, + allowedFunctionNames: ['controlLight'], + } + }, + tools: [{functionDeclarations: [controlLightDeclaration]}] + } + }); + + console.log(response.functionCalls); +} + +main(); +``` + +#### Model Context Protocol (MCP) support (experimental) + +Built-in [MCP](https://modelcontextprotocol.io/introduction) support is an +experimental feature. You can pass a local MCP server as a tool directly. + +```javascript +import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai'; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; + +// Create server parameters for stdio connection +const serverParams = new StdioClientTransport({ + command: "npx", // Executable + args: ["-y", "@philschmid/weather-mcp"] // MCP Server +}); + +const client = new Client( + { + name: "example-client", + version: "1.0.0" + } +); + +// Configure the client +const ai = new GoogleGenAI({}); + +// Initialize the connection between client and server +await client.connect(serverParams); + +// Send request to the model with MCP tools +const response = await ai.models.generateContent({ + model: "gemini-2.5-flash", + contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, + config: { + tools: [mcpToTool(client)], // uses the session, will automatically call the tool using automatic function calling + }, +}); +console.log(response.text); + +// Close the connection +await client.close(); +``` + +### Generate Content + +#### How to structure `contents` argument for `generateContent` + +The SDK allows you to specify the following types in the `contents` parameter: + +#### Content + +- `Content`: The SDK will wrap the singular `Content` instance in an array which +contains only the given content instance +- `Content[]`: No transformation happens + +#### Part + +Parts will be aggregated on a singular Content, with role 'user'. + +- `Part | string`: The SDK will wrap the `string` or `Part` in a `Content` +instance with role 'user'. +- `Part[] | string[]`: The SDK will wrap the full provided list into a single +`Content` with role 'user'. + +**_NOTE:_** This doesn't apply to `FunctionCall` and `FunctionResponse` parts, +if you are specifying those, you need to explicitly provide the full +`Content[]` structure making it explicit which Parts are 'spoken' by the model, +or the user. The SDK will throw an exception if you try this. + +## Error Handling + +To handle errors raised by the API, the SDK provides this [ApiError](https://github.com/googleapis/js-genai/blob/main/src/errors.ts) class. + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + await ai.models.generateContent({ + model: 'non-existent-model', + contents: 'Write a 100-word poem.', + }).catch((e) => { + console.error('error name: ', e.name); + console.error('error message: ', e.message); + console.error('error status: ', e.status); + }); +} + +main(); +``` + +## How is this different from the other Google AI SDKs +This SDK (`@google/genai`) is Google Deepmind’s "vanilla" SDK for its generative +AI offerings, and is where Google Deepmind adds new AI features. + +Models hosted either on the [Vertex AI platform](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) or the [Gemini Developer platform](https://ai.google.dev/gemini-api/docs) are accessible through this SDK. + +Other SDKs may be offering additional AI frameworks on top of this SDK, or may +be targeting specific project environments (like Firebase). + +The `@google/generative_language` and `@google-cloud/vertexai` SDKs are previous +iterations of this SDK and are no longer receiving new Gemini 2.0+ features. + diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/genai.d.ts b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/genai.d.ts new file mode 100644 index 0000000..665c84e --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/genai.d.ts @@ -0,0 +1,7721 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** Optional parameters for tunings.cancel method. */ +export declare interface CancelTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the cancel method. */ +export declare interface CancelTuningJobParameters { + /** The resource name of the tuning job. */ + name: string; + /** Optional parameters for the request. */ + config?: CancelTuningJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the editing mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + VALIDATED = "VALIDATED" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with + unchanged inputs, the prediction results will be consistent. Otherwise, + a random RNG seed will be used each time to produce a different + result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and + 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are + supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific + ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation + progress. */ + pubsubTopic?: string; + /** Explicitly state what should not be included in the generated + videos. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. + Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The generated videos. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; + /** A set of source input(s) for video generation. */ + source?: GenerateVideosSource; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** A set of source input(s) for video generation. */ +export declare interface GenerateVideosSource { + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Private method for generating images. + */ + private generateImagesInternal; + /** + * Private method for editing an image. + */ + private editImageInternal; + /** + * Private method for upscaling an image. + */ + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Private method for generating videos. + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** Used to override the default configuration. */ + config?: GetOperationConfig; + /** The operation to be retrieved. */ + operation: U; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** Whether to add a SynthID watermark to the generated images. */ + addWatermark?: boolean; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. */ + categories?: string[]; + /** List of scores of each categories. */ + scores?: number[]; + /** Internal use only. */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelTuningJobParameters): Promise; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoGenerationReferenceType, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosSource, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + Operation, + GenerateVideosOperation, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + CancelTuningJobConfig, + CancelTuningJobParameters, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationFromAPIResponseParameters, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + OperationGetParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example ``video/mp4``. */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. */ + referenceType?: VideoGenerationReferenceType; +} + +/** Enum for the reference type of a video generation reference image. */ +export declare enum VideoGenerationReferenceType { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + ASSET = "ASSET", + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + STYLE = "STYLE" +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.cjs b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.cjs new file mode 100644 index 0000000..4c44917 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.cjs @@ -0,0 +1,18894 @@ +'use strict'; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(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"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * 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"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Tuning mode. */ +exports.TuningMode = void 0; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(exports.TuningMode || (exports.TuningMode = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(exports.FeatureSelectionPreference || (exports.FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that represents the segmentation mode. */ +exports.SegmentMode = void 0; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(exports.SegmentMode || (exports.SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +exports.VideoGenerationReferenceType = void 0; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(exports.VideoGenerationReferenceType || (exports.VideoGenerationReferenceType = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(exports.FunctionResponseScheduling || (exports.FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The mode of music generation. */ +exports.MusicGenerationMode = void 0; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(exports.MusicGenerationMode || (exports.MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(exports.Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(exports.Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +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, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + 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]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false 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; + } + return isValidContent(content); +} +function isValidContent(content) { + 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; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.17.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToMldev(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } + else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(exports.PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.RecontextImageResponse = RecontextImageResponse; +exports.ReplayResponse = ReplayResponse; +exports.SegmentImageResponse = SegmentImageResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs new file mode 100644 index 0000000..21829c8 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs @@ -0,0 +1,18834 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +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 = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * 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"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +var VideoGenerationReferenceType; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +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, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + 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]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false 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; + } + return isValidContent(content); +} +function isValidContent(content) { + 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; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.17.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToMldev(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationReferenceType, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs.map b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs.map new file mode 100644 index 0000000..9be1ea1 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/_base_url.ts","../src/_common.ts","../src/_base_transformers.ts","../src/types.ts","../src/_transformers.ts","../src/converters/_batches_converters.ts","../src/pagers.ts","../src/batches.ts","../src/converters/_caches_converters.ts","../src/caches.ts","../src/chats.ts","../src/errors.ts","../src/_api_client.ts","../src/cross/_cross_error.ts","../src/cross/_cross_downloader.ts","../src/cross/_cross_uploader.ts","../src/cross/_cross_websocket.ts","../src/converters/_files_converters.ts","../src/files.ts","../src/converters/_live_converters.ts","../src/converters/_models_converters.ts","../src/mcp/_mcp.ts","../src/music.ts","../src/live.ts","../src/_afc.ts","../src/models.ts","../src/converters/_operations_converters.ts","../src/operations.ts","../src/converters/_tokens_converters.ts","../src/tokens.ts","../src/converters/_tunings_converters.ts","../src/tunings.ts","../src/web/_web_auth.ts","../src/client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n /**\n * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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\".\n */\n VALIDATED = 'VALIDATED',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the editing mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum for the reference type of a video generation reference image. */\nexport enum VideoGenerationReferenceType {\n /**\n * A reference image that provides assets to the generated video,\n such as the scene, an object, a character, etc.\n */\n ASSET = 'ASSET',\n /**\n * A reference image that provides aesthetics including colors,\n lighting, texture, etc., to be used as the style of the generated video,\n such as 'anime', 'photography', 'origami', etc.\n */\n STYLE = 'STYLE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models). */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both. */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories. */\n categories?: string[];\n /** List of scores of each categories. */\n scores?: number[];\n /** Internal use only. */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data. */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response. */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content. */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled. */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True. */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** Whether to add a SynthID watermark to the generated images. */\n addWatermark?: boolean;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example ``video/mp4``. */\n mimeType?: string;\n}\n\n/** A set of source input(s) for video generation. */\nexport declare interface GenerateVideosSource {\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image. */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. */\n referenceType?: VideoGenerationReferenceType;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with\n unchanged inputs, the prediction results will be consistent. Otherwise,\n a random RNG seed will be used each time to produce a different\n result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and\n 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are\n supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific\n ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation\n progress. */\n pubsubTopic?: string;\n /** Explicitly state what should not be included in the generated\n videos. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos.\n Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n /** A set of source input(s) for video generation. */\n source?: GenerateVideosSource;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The generated videos. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\nexport /** Optional parameters for tunings.get method. */\ndeclare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\n/** Optional parameters for tunings.cancel method. */\nexport declare interface CancelTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the cancel method. */\nexport declare interface CancelTuningJobParameters {\n /** The resource name of the tuning job. */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelTuningJobConfig;\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression. Only applicable if the\n ``output_mime_type`` is ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n /** The operation to be retrieved. */\n operation: U;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (mcpToolSchema['outputSchema']) {\n functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema'];\n }\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\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 }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.17.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function crossError(): Error {\n // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports\n return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:\n\n*Enabling conditional exports for your project [recommended]*\n\n*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.\n`);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport class CrossDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\nimport {crossError} from './_cross_error.js';\n\nexport class CrossWebSocketFactory implements WebSocketFactory {\n create(\n _url: string,\n _headers: Record,\n _callbacks: WebSocketCallbacks,\n ): Ws {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(\n fromObject: types.DeleteFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteFileResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteFileResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToMldev(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (parentObject !== undefined && fromVideo != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * source: {\n * prompt: 'A neon hologram of a cat driving at top speed',\n * },\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n if ((params.prompt || params.image || params.video) && params.source) {\n throw new Error(\n 'Source and prompt/image/video are mutually exclusive. Please only use source.',\n );\n }\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for generating images.\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for editing an image.\n */\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for upscaling an image.\n */\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for generating videos.\n */\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function fetchPredictOperationParametersToMldev(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['operationName']) !== undefined) {\n throw new Error('operationName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['resourceName']) !== undefined) {\n throw new Error('resourceName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToMldev(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToVertex(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Cancels a tuning job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelTuningJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from './_api_client.js';\nimport {Batches} from './batches.js';\nimport {Caches} from './caches.js';\nimport {Chats} from './chats.js';\nimport {CrossDownloader} from './cross/_cross_downloader.js';\nimport {crossError} from './cross/_cross_error.js';\nimport {CrossUploader} from './cross/_cross_uploader.js';\nimport {CrossWebSocketFactory} from './cross/_cross_websocket.js';\nimport {Files} from './files.js';\nimport {Live} from './live.js';\nimport {Models} from './models.js';\nimport {Operations} from './operations.js';\nimport {Tokens} from './tokens.js';\nimport {Tunings} from './tunings.js';\nimport {HttpOptions} from './types.js';\nimport {WebAuth} from './web/_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * Google Gen AI SDK's configuration options.\n *\n * See {@link GoogleGenAI} for usage samples.\n */\nexport interface GoogleGenAIOptions {\n /**\n * Optional. Determines whether to use the Vertex AI or the Gemini API.\n *\n * @remarks\n * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used.\n * When false, the {@link https://ai.google.dev/api | Gemini API} will be used.\n *\n * If unset, default SDK behavior is to use the Gemini API service.\n */\n vertexai?: boolean;\n /**\n * Optional. The Google Cloud project ID for Vertex AI clients.\n *\n * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n location?: string;\n /**\n * The API Key, required for Gemini API clients.\n *\n * @remarks\n * Required on browser runtimes.\n */\n apiKey?: string;\n /**\n * Optional. The API version to use.\n *\n * @remarks\n * If unset, the default API version will be used.\n */\n apiVersion?: string;\n /**\n * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients.\n *\n * @remarks\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}.\n *\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n googleAuthOptions?: GoogleAuthOptions;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API}\n * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set,\n * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error(\n `An API Key must be set when running in an unspecified environment.\\n + ${crossError().message}`,\n );\n }\n this.vertexai = options.vertexai ?? false;\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',\n uploader: new CrossUploader(),\n downloader: new CrossDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.batches = new Batches(this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.cancelTuningJobParametersToVertex","converters.cancelTuningJobParametersToMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOper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E,IAAI,aAAa,EAAE;YAC7B,UAAU,EAAE,IAAI,eAAe,EAAE;AAClC,SAAA,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;AACxC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,qBAAqB,EAAE,CAAC;AACvE,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1C,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;QAChD,IAAI,CAAC,UAAU,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC5C,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.cjs b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.cjs new file mode 100644 index 0000000..188c299 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.cjs @@ -0,0 +1,19312 @@ +'use strict'; + +var googleAuthLibrary = require('google-auth-library'); +var fs = require('fs'); +var node_stream = require('node:stream'); +var NodeWs = require('ws'); +var fs$1 = require('fs/promises'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var NodeWs__namespace = /*#__PURE__*/_interopNamespaceDefault(NodeWs); +var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1); + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(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"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * 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"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Tuning mode. */ +exports.TuningMode = void 0; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(exports.TuningMode || (exports.TuningMode = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(exports.FeatureSelectionPreference || (exports.FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that represents the segmentation mode. */ +exports.SegmentMode = void 0; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(exports.SegmentMode || (exports.SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +exports.VideoGenerationReferenceType = void 0; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(exports.VideoGenerationReferenceType || (exports.VideoGenerationReferenceType = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(exports.FunctionResponseScheduling || (exports.FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The mode of music generation. */ +exports.MusicGenerationMode = void 0; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(exports.MusicGenerationMode || (exports.MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(exports.Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(exports.Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +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, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + 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]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false 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; + } + return isValidContent(content); +} +function isValidContent(content) { + 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; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToMldev(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.17.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } + else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(exports.PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new googleAuthLibrary.GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error('Trying to set API key header but apiKey is not set'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error('Trying to set google-auth headers but googleAuth is unset'); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } + else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } + else if ((typeof authOptions.scopes === 'string' && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) { + throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = fs.createWriteStream(params.downloadPath); + node_stream.Readable.fromWeb(response.responseInternal.body).pipe(writer); + } + else { + fs.writeFile(params.downloadPath, response, { encoding: 'base64' }, (error) => { + if (error) { + throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`); + } + }); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: 'GET', + queryParams: { + 'alt': 'media', + }, + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else if (isGeneratedVideo(params.file)) { + const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download generated video, Uri or videoBytes not found.'); + } + } + else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download video, Uri or videoBytes not found.'); + } + } + else { + throw new Error('Unsupported file type'); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs__namespace.WebSocket(this.url, { headers: this.headers }); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === 'string') { + const originalStat = await fs__namespace.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 'aac': 'audio/aac', + 'abw': 'application/x-abiword', + 'arc': 'application/x-freearc', + 'avi': 'video/x-msvideo', + 'azw': 'application/vnd.amazon.ebook', + 'bin': 'application/octet-stream', + 'bmp': 'image/bmp', + 'bz': 'application/x-bzip', + 'bz2': 'application/x-bzip2', + 'csh': 'application/x-csh', + 'css': 'text/css', + 'csv': 'text/csv', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eot': 'application/vnd.ms-fontobject', + 'epub': 'application/epub+zip', + 'gz': 'application/gzip', + 'gif': 'image/gif', + 'htm': 'text/html', + 'html': 'text/html', + 'ico': 'image/vnd.microsoft.icon', + 'ics': 'text/calendar', + 'jar': 'application/java-archive', + 'jpeg': 'image/jpeg', + 'jpg': 'image/jpeg', + 'js': 'text/javascript', + 'json': 'application/json', + 'jsonld': 'application/ld+json', + 'kml': 'application/vnd.google-earth.kml+xml', + 'kmz': 'application/vnd.google-earth.kmz+xml', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'mpeg': 'video/mpeg', + 'mpkg': 'application/vnd.apple.installer+xml', + 'odt': 'application/vnd.oasis.opendocument.text', + 'oga': 'audio/ogg', + 'ogv': 'video/ogg', + 'ogx': 'application/ogg', + 'opus': 'audio/opus', + 'otf': 'font/otf', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'php': 'application/x-httpd-php', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'rar': 'application/vnd.rar', + 'rtf': 'application/rtf', + 'sh': 'application/x-sh', + 'svg': 'image/svg+xml', + 'swf': 'application/x-shockwave-flash', + 'tar': 'application/x-tar', + 'tif': 'image/tiff', + 'tiff': 'image/tiff', + 'ts': 'video/mp2t', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'vsd': 'application/vnd.visio', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'webp': 'image/webp', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xhtml': 'application/xhtml+xml', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml': 'application/xml', + 'xul': 'application/vnd.mozilla.xul+xml', + 'zip': 'application/zip', + '3gp': 'video/3gpp', + '3g2': 'video/3gpp2', + '7z': 'application/x-7z-compressed', + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + try { + fileHandle = await fs__namespace.open(file, 'r'); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset); + if (bytesRead !== chunkSize) { + throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(bytesRead), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error('Project/location and API key are mutually exclusive in the client initializer.'); + } + this.vertexai = + (_b = (_a = options.vertexai) !== null && _a !== void 0 ? _a : getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI')) !== null && _b !== void 0 ? _b : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ((_f = options.googleAuthOptions) === null || _f === void 0 ? void 0 : _f.credentials) { + // Explicit credentials take precedence over implicit api_key. + console.debug('The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.'); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug('The user provided Vertex AI API key will take precedence over' + + ' the project/location from the environment variables.'); + this.project = undefined; + this.location = undefined; + } + else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug('The user provided project/location will take precedence over' + + ' the API key from the environment variables.'); + this.apiKey = undefined; + } + else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug('The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.'); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, getEnv('GOOGLE_VERTEX_BASE_URL'), getEnv('GOOGLE_GEMINI_BASE_URL')); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = (_b = (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv('GOOGLE_API_KEY'); + const envGeminiApiKey = getEnv('GEMINI_API_KEY'); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn('Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'); + } + return envGoogleApiKey || envGeminiApiKey || undefined; +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.RecontextImageResponse = RecontextImageResponse; +exports.ReplayResponse = ReplayResponse; +exports.SegmentImageResponse = SegmentImageResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs new file mode 100644 index 0000000..b68bfc2 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs @@ -0,0 +1,19232 @@ +import { GoogleAuth } from 'google-auth-library'; +import { createWriteStream, writeFile } from 'fs'; +import { Readable } from 'node:stream'; +import * as NodeWs from 'ws'; +import * as fs from 'fs/promises'; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +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 = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * 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"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +var VideoGenerationReferenceType; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +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, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + 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]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false 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; + } + return isValidContent(content); +} +function isValidContent(content) { + 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; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToMldev(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.17.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error('Trying to set API key header but apiKey is not set'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error('Trying to set google-auth headers but googleAuth is unset'); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } + else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } + else if ((typeof authOptions.scopes === 'string' && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) { + throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = createWriteStream(params.downloadPath); + Readable.fromWeb(response.responseInternal.body).pipe(writer); + } + else { + writeFile(params.downloadPath, response, { encoding: 'base64' }, (error) => { + if (error) { + throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`); + } + }); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: 'GET', + queryParams: { + 'alt': 'media', + }, + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else if (isGeneratedVideo(params.file)) { + const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download generated video, Uri or videoBytes not found.'); + } + } + else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download video, Uri or videoBytes not found.'); + } + } + else { + throw new Error('Unsupported file type'); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs.WebSocket(this.url, { headers: this.headers }); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === 'string') { + const originalStat = await fs.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 'aac': 'audio/aac', + 'abw': 'application/x-abiword', + 'arc': 'application/x-freearc', + 'avi': 'video/x-msvideo', + 'azw': 'application/vnd.amazon.ebook', + 'bin': 'application/octet-stream', + 'bmp': 'image/bmp', + 'bz': 'application/x-bzip', + 'bz2': 'application/x-bzip2', + 'csh': 'application/x-csh', + 'css': 'text/css', + 'csv': 'text/csv', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eot': 'application/vnd.ms-fontobject', + 'epub': 'application/epub+zip', + 'gz': 'application/gzip', + 'gif': 'image/gif', + 'htm': 'text/html', + 'html': 'text/html', + 'ico': 'image/vnd.microsoft.icon', + 'ics': 'text/calendar', + 'jar': 'application/java-archive', + 'jpeg': 'image/jpeg', + 'jpg': 'image/jpeg', + 'js': 'text/javascript', + 'json': 'application/json', + 'jsonld': 'application/ld+json', + 'kml': 'application/vnd.google-earth.kml+xml', + 'kmz': 'application/vnd.google-earth.kmz+xml', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'mpeg': 'video/mpeg', + 'mpkg': 'application/vnd.apple.installer+xml', + 'odt': 'application/vnd.oasis.opendocument.text', + 'oga': 'audio/ogg', + 'ogv': 'video/ogg', + 'ogx': 'application/ogg', + 'opus': 'audio/opus', + 'otf': 'font/otf', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'php': 'application/x-httpd-php', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'rar': 'application/vnd.rar', + 'rtf': 'application/rtf', + 'sh': 'application/x-sh', + 'svg': 'image/svg+xml', + 'swf': 'application/x-shockwave-flash', + 'tar': 'application/x-tar', + 'tif': 'image/tiff', + 'tiff': 'image/tiff', + 'ts': 'video/mp2t', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'vsd': 'application/vnd.visio', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'webp': 'image/webp', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xhtml': 'application/xhtml+xml', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml': 'application/xml', + 'xul': 'application/vnd.mozilla.xul+xml', + 'zip': 'application/zip', + '3gp': 'video/3gpp', + '3g2': 'video/3gpp2', + '7z': 'application/x-7z-compressed', + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + try { + fileHandle = await fs.open(file, 'r'); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset); + if (bytesRead !== chunkSize) { + throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(bytesRead), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error('Project/location and API key are mutually exclusive in the client initializer.'); + } + this.vertexai = + (_b = (_a = options.vertexai) !== null && _a !== void 0 ? _a : getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI')) !== null && _b !== void 0 ? _b : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ((_f = options.googleAuthOptions) === null || _f === void 0 ? void 0 : _f.credentials) { + // Explicit credentials take precedence over implicit api_key. + console.debug('The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.'); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug('The user provided Vertex AI API key will take precedence over' + + ' the project/location from the environment variables.'); + this.project = undefined; + this.location = undefined; + } + else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug('The user provided project/location will take precedence over' + + ' the API key from the environment variables.'); + this.apiKey = undefined; + } + else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug('The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.'); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, getEnv('GOOGLE_VERTEX_BASE_URL'), getEnv('GOOGLE_GEMINI_BASE_URL')); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = (_b = (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv('GOOGLE_API_KEY'); + const envGeminiApiKey = getEnv('GEMINI_API_KEY'); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn('Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'); + } + return envGoogleApiKey || envGeminiApiKey || undefined; +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationReferenceType, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs.map b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs.map new file mode 100644 index 0000000..c3fd456 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/node/_node_auth.ts","../../src/node/_node_downloader.ts","../../src/node/_node_websocket.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/cross/_cross_uploader.ts","../../src/node/_node_uploader.ts","../../src/node/node_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n /**\n * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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\".\n */\n VALIDATED = 'VALIDATED',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the editing mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum for the reference type of a video generation reference image. */\nexport enum VideoGenerationReferenceType {\n /**\n * A reference image that provides assets to the generated video,\n such as the scene, an object, a character, etc.\n */\n ASSET = 'ASSET',\n /**\n * A reference image that provides aesthetics including colors,\n lighting, texture, etc., to be used as the style of the generated video,\n such as 'anime', 'photography', 'origami', etc.\n */\n STYLE = 'STYLE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models). */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both. */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories. */\n categories?: string[];\n /** List of scores of each categories. */\n scores?: number[];\n /** Internal use only. */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data. */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response. */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content. */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled. */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True. */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** Whether to add a SynthID watermark to the generated images. */\n addWatermark?: boolean;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example ``video/mp4``. */\n mimeType?: string;\n}\n\n/** A set of source input(s) for video generation. */\nexport declare interface GenerateVideosSource {\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image. */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. */\n referenceType?: VideoGenerationReferenceType;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with\n unchanged inputs, the prediction results will be consistent. Otherwise,\n a random RNG seed will be used each time to produce a different\n result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and\n 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are\n supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific\n ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation\n progress. */\n pubsubTopic?: string;\n /** Explicitly state what should not be included in the generated\n videos. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos.\n Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n /** A set of source input(s) for video generation. */\n source?: GenerateVideosSource;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The generated videos. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\nexport /** Optional parameters for tunings.get method. */\ndeclare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\n/** Optional parameters for tunings.cancel method. */\nexport declare interface CancelTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the cancel method. */\nexport declare interface CancelTuningJobParameters {\n /** The resource name of the tuning job. */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelTuningJobConfig;\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression. Only applicable if the\n ``output_mime_type`` is ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n /** The operation to be retrieved. */\n operation: U;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (mcpToolSchema['outputSchema']) {\n functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema'];\n }\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\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 }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(\n fromObject: types.DeleteFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteFileResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteFileResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToMldev(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (parentObject !== undefined && fromVideo != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.17.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * source: {\n * prompt: 'A neon hologram of a cat driving at top speed',\n * },\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n if ((params.prompt || params.image || params.video) && params.source) {\n throw new Error(\n 'Source and prompt/image/video are mutually exclusive. Please only use source.',\n );\n }\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for generating images.\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for editing an image.\n */\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for upscaling an image.\n */\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for generating videos.\n */\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function fetchPredictOperationParametersToMldev(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['operationName']) !== undefined) {\n throw new Error('operationName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['resourceName']) !== undefined) {\n throw new Error('resourceName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\nconst REQUIRED_VERTEX_AI_SCOPE =\n 'https://www.googleapis.com/auth/cloud-platform';\n\nexport interface NodeAuthOptions {\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. These are the authentication options provided by google-auth-library for Vertex AI users.\n * Complete list of authentication options are documented in the\n * GoogleAuthOptions interface:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts.\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\nexport class NodeAuth implements Auth {\n private readonly googleAuth?: GoogleAuth;\n private readonly apiKey?: string;\n\n constructor(opts: NodeAuthOptions) {\n if (opts.apiKey !== undefined) {\n this.apiKey = opts.apiKey;\n return;\n }\n const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);\n this.googleAuth = new GoogleAuth(vertexAuthOptions);\n }\n\n async addAuthHeaders(headers: Headers): Promise {\n if (this.apiKey !== undefined) {\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n this.addKeyHeader(headers);\n return;\n }\n\n return this.addGoogleAuthHeaders(headers);\n }\n\n private addKeyHeader(headers: Headers) {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n if (this.apiKey === undefined) {\n // This should never happen, this method is only called\n // when apiKey is set.\n throw new Error('Trying to set API key header but apiKey is not set');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n\n private async addGoogleAuthHeaders(headers: Headers): Promise {\n if (this.googleAuth === undefined) {\n // This should never happen, addGoogleAuthHeaders should only be\n // called when there is no apiKey set and in these cases googleAuth\n // is set.\n throw new Error(\n 'Trying to set google-auth headers but googleAuth is unset',\n );\n }\n const authHeaders = await this.googleAuth.getRequestHeaders();\n for (const key in authHeaders) {\n if (headers.get(key) !== null) {\n continue;\n }\n headers.append(key, authHeaders[key]);\n }\n }\n}\n\nfunction buildGoogleAuthOptions(\n googleAuthOptions?: GoogleAuthOptions,\n): GoogleAuthOptions {\n let authOptions: GoogleAuthOptions;\n if (!googleAuthOptions) {\n authOptions = {\n scopes: [REQUIRED_VERTEX_AI_SCOPE],\n };\n return authOptions;\n } else {\n authOptions = googleAuthOptions;\n if (!authOptions.scopes) {\n authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];\n return authOptions;\n } else if (\n (typeof authOptions.scopes === 'string' &&\n authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||\n (Array.isArray(authOptions.scopes) &&\n authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)\n ) {\n throw new Error(\n `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`,\n );\n }\n return authOptions;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {createWriteStream, writeFile} from 'fs';\nimport {Readable} from 'node:stream';\nimport type {ReadableStream} from 'node:stream/web';\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {isGeneratedVideo, isVideo, tFileName} from '../_transformers.js';\nimport {\n DownloadFileParameters,\n GeneratedVideo,\n HttpResponse,\n Video,\n} from '../types.js';\n\nexport class NodeDownloader implements Downloader {\n async download(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n ): Promise {\n if (params.downloadPath) {\n const response = await downloadFile(params, apiClient);\n if (response instanceof HttpResponse) {\n const writer = createWriteStream(params.downloadPath);\n Readable.fromWeb(\n response.responseInternal.body as ReadableStream,\n ).pipe(writer);\n } else {\n writeFile(\n params.downloadPath,\n response as string,\n {encoding: 'base64'},\n (error) => {\n if (error) {\n throw new Error(\n `Failed to write file to ${params.downloadPath}: ${error}`,\n );\n }\n },\n );\n }\n }\n }\n}\n\nasync function downloadFile(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n): Promise {\n const name = tFileName(params.file);\n if (name !== undefined) {\n return await apiClient.request({\n path: `files/${name}:download`,\n httpMethod: 'GET',\n queryParams: {\n 'alt': 'media',\n },\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else if (isGeneratedVideo(params.file)) {\n const videoBytes = (params.file as GeneratedVideo).video?.videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error(\n 'Failed to download generated video, Uri or videoBytes not found.',\n );\n }\n } else if (isVideo(params.file)) {\n const videoBytes = (params.file as Video).videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error('Failed to download video, Uri or videoBytes not found.');\n }\n } else {\n throw new Error('Unsupported file type');\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as NodeWs from 'ws';\n\nimport {\n WebSocket,\n WebSocketCallbacks,\n WebSocketFactory,\n} from '../_websocket.js';\n\nexport class NodeWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): WebSocket {\n return new NodeWebSocket(url, headers, callbacks);\n }\n}\n\nexport class NodeWebSocket implements WebSocket {\n private ws?: NodeWs.WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new NodeWs.WebSocket(this.url, {headers: this.headers});\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToMldev(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToVertex(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Cancels a tuning job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelTuningJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs/promises';\n\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {\n DELAY_MULTIPLIER,\n INITIAL_RETRY_DELAY_MS,\n MAX_CHUNK_SIZE,\n MAX_RETRY_COUNT,\n X_GOOG_UPLOAD_STATUS_HEADER_FIELD,\n getBlobStat,\n sleep,\n uploadBlob,\n} from '../cross/_cross_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nexport class NodeUploader implements Uploader {\n async stat(file: string | Blob): Promise {\n const fileStat: FileStat = {size: 0, type: undefined};\n if (typeof file === 'string') {\n const originalStat = await fs.stat(file);\n fileStat.size = originalStat.size;\n fileStat.type = this.inferMimeType(file);\n return fileStat;\n } else {\n return await getBlobStat(file);\n }\n }\n\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n return await this.uploadFileFromPath(file, uploadUrl, apiClient);\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n /**\n * Infers the MIME type of a file based on its extension.\n *\n * @param filePath The path to the file.\n * @returns The MIME type of the file, or undefined if it cannot be inferred.\n */\n private inferMimeType(filePath: string): string | undefined {\n // Get the file extension.\n const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1);\n\n // Create a map of file extensions to MIME types.\n const mimeTypes: {[key: string]: string} = {\n 'aac': 'audio/aac',\n 'abw': 'application/x-abiword',\n 'arc': 'application/x-freearc',\n 'avi': 'video/x-msvideo',\n 'azw': 'application/vnd.amazon.ebook',\n 'bin': 'application/octet-stream',\n 'bmp': 'image/bmp',\n 'bz': 'application/x-bzip',\n 'bz2': 'application/x-bzip2',\n 'csh': 'application/x-csh',\n 'css': 'text/css',\n 'csv': 'text/csv',\n 'doc': 'application/msword',\n 'docx':\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'eot': 'application/vnd.ms-fontobject',\n 'epub': 'application/epub+zip',\n 'gz': 'application/gzip',\n 'gif': 'image/gif',\n 'htm': 'text/html',\n 'html': 'text/html',\n 'ico': 'image/vnd.microsoft.icon',\n 'ics': 'text/calendar',\n 'jar': 'application/java-archive',\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'jsonld': 'application/ld+json',\n 'kml': 'application/vnd.google-earth.kml+xml',\n 'kmz': 'application/vnd.google-earth.kmz+xml',\n 'mjs': 'text/javascript',\n 'mp3': 'audio/mpeg',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'mpkg': 'application/vnd.apple.installer+xml',\n 'odt': 'application/vnd.oasis.opendocument.text',\n 'oga': 'audio/ogg',\n 'ogv': 'video/ogg',\n 'ogx': 'application/ogg',\n 'opus': 'audio/opus',\n 'otf': 'font/otf',\n 'png': 'image/png',\n 'pdf': 'application/pdf',\n 'php': 'application/x-httpd-php',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx':\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'rar': 'application/vnd.rar',\n 'rtf': 'application/rtf',\n 'sh': 'application/x-sh',\n 'svg': 'image/svg+xml',\n 'swf': 'application/x-shockwave-flash',\n 'tar': 'application/x-tar',\n 'tif': 'image/tiff',\n 'tiff': 'image/tiff',\n 'ts': 'video/mp2t',\n 'ttf': 'font/ttf',\n 'txt': 'text/plain',\n 'vsd': 'application/vnd.visio',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n 'webm': 'video/webm',\n 'webp': 'image/webp',\n 'woff': 'font/woff',\n 'woff2': 'font/woff2',\n 'xhtml': 'application/xhtml+xml',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx':\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xml': 'application/xml',\n 'xul': 'application/vnd.mozilla.xul+xml',\n 'zip': 'application/zip',\n '3gp': 'video/3gpp',\n '3g2': 'video/3gpp2',\n '7z': 'application/x-7z-compressed',\n };\n\n // Look up the MIME type based on the file extension.\n const mimeType = mimeTypes[fileExtension.toLowerCase()];\n\n // Return the MIME type.\n return mimeType;\n }\n\n private async uploadFileFromPath(\n file: string,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n let fileHandle: fs.FileHandle | undefined;\n try {\n fileHandle = await fs.open(file, 'r');\n if (!fileHandle) {\n throw new Error(`Failed to open file`);\n }\n fileSize = (await fileHandle.stat()).size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n const buffer = new Uint8Array(chunkSize);\n const {bytesRead: bytesRead} = await fileHandle.read(\n buffer,\n 0,\n chunkSize,\n offset,\n );\n\n if (bytesRead !== chunkSize) {\n throw new Error(\n `Failed to read ${chunkSize} bytes from file at offset ${\n offset\n }. bytes actually read: ${bytesRead}`,\n );\n }\n\n const chunk = new Blob([buffer]);\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(bytesRead),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += bytesRead;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (\n response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active'\n ) {\n break;\n }\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error(\n 'Failed to upload file: Upload status is not finalized.',\n );\n }\n return responseJson['file'] as File;\n } finally {\n // Ensure the file handle is always closed\n if (fileHandle) {\n await fileHandle.close();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {NodeAuth} from '../node/_node_auth.js';\nimport {NodeDownloader} from '../node/_node_downloader.js';\nimport {NodeWebSocketFactory} from '../node/_node_websocket.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {NodeUploader} from './_node_uploader.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} must be set, or a {@link\n * GoogleGenAIOptions.apiKey} must be set when using Express Mode.\n *\n * Explicitly passed in values in {@link GoogleGenAIOptions} will always take\n * precedence over environment variables. If both project/location and api_key\n * exist in the environment variables, the project/location will be used.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly googleAuthOptions?: GoogleAuthOptions;\n private readonly project?: string;\n private readonly location?: string;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n // Validate explicitly set initializer values.\n if ((options.project || options.location) && options.apiKey) {\n throw new Error(\n 'Project/location and API key are mutually exclusive in the client initializer.',\n );\n }\n\n this.vertexai =\n options.vertexai ?? getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI') ?? false;\n const envApiKey = getApiKeyFromEnv();\n const envProject = getEnv('GOOGLE_CLOUD_PROJECT');\n const envLocation = getEnv('GOOGLE_CLOUD_LOCATION');\n\n this.apiKey = options.apiKey ?? envApiKey;\n this.project = options.project ?? envProject;\n this.location = options.location ?? envLocation;\n\n // Handle when to use Vertex AI in express mode (api key)\n if (options.vertexai) {\n if (options.googleAuthOptions?.credentials) {\n // Explicit credentials take precedence over implicit api_key.\n console.debug(\n 'The user provided Google Cloud credentials will take precedence' +\n ' over the API key from the environment variable.',\n );\n this.apiKey = undefined;\n }\n // Explicit api_key and explicit project/location already handled above.\n if ((envProject || envLocation) && options.apiKey) {\n // Explicit api_key takes precedence over implicit project/location.\n console.debug(\n 'The user provided Vertex AI API key will take precedence over' +\n ' the project/location from the environment variables.',\n );\n this.project = undefined;\n this.location = undefined;\n } else if ((options.project || options.location) && envApiKey) {\n // Explicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The user provided project/location will take precedence over' +\n ' the API key from the environment variables.',\n );\n this.apiKey = undefined;\n } else if ((envProject || envLocation) && envApiKey) {\n // Implicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The project/location from the environment variables will take' +\n ' precedence over the API key from the environment variables.',\n );\n this.apiKey = undefined;\n }\n }\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n getEnv('GOOGLE_VERTEX_BASE_URL'),\n getEnv('GOOGLE_GEMINI_BASE_URL'),\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new NodeAuth({\n apiKey: this.apiKey,\n googleAuthOptions: options.googleAuthOptions,\n });\n this.apiClient = new ApiClient({\n auth: auth,\n project: this.project,\n location: this.location,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version,\n uploader: new NodeUploader(),\n downloader: new NodeDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n\nfunction getEnv(env: string): string | undefined {\n return process?.env?.[env]?.trim() ?? undefined;\n}\n\nfunction getBooleanEnv(env: string): boolean {\n return stringToBoolean(getEnv(env));\n}\n\nfunction stringToBoolean(str?: string): boolean {\n if (str === undefined) {\n return false;\n }\n return str.toLowerCase() === 'true';\n}\n\nfunction getApiKeyFromEnv(): string | undefined {\n const envGoogleApiKey = getEnv('GOOGLE_API_KEY');\n const envGeminiApiKey = getEnv('GEMINI_API_KEY');\n if (envGoogleApiKey && envGeminiApiKey) {\n console.warn(\n 'Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.',\n );\n }\n return envGoogleApiKey || envGeminiApiKey || undefined;\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.cancelTuningJobParametersToVertex","converters.cancelTuningJobParametersToMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOperationFromMldev"],"mappings":";;;;;;AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AAAM,aAAA;AACL,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AACF;IAED,OAAO,WAAW,CAAC,OAAO;AAC5B;;AC5EA;;;;AAIG;MAEU,UAAU,CAAA;AAAG;AAEV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;IAGjC,MAAM,KAAK,GAAG,cAAc;;IAG5B,OAAO,cAAc,CAAC,OAAO,CAAC,K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rC;AAEA,SAAS,gBAAgB,GAAA;AACvB,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;AAChD,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;IAChD,IAAI,eAAe,IAAI,eAAe,EAAE;AACtC,QAAA,OAAO,CAAC,IAAI,CACV,uEAAuE,CACxE;AACF;AACD,IAAA,OAAO,eAAe,IAAI,eAAe,IAAI,SAAS;AACxD;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/node.d.ts b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/node.d.ts new file mode 100644 index 0000000..ad5b062 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/node/node.d.ts @@ -0,0 +1,7733 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** Optional parameters for tunings.cancel method. */ +export declare interface CancelTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the cancel method. */ +export declare interface CancelTuningJobParameters { + /** The resource name of the tuning job. */ + name: string; + /** Optional parameters for the request. */ + config?: CancelTuningJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the editing mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + VALIDATED = "VALIDATED" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with + unchanged inputs, the prediction results will be consistent. Otherwise, + a random RNG seed will be used each time to produce a different + result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and + 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are + supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific + ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation + progress. */ + pubsubTopic?: string; + /** Explicitly state what should not be included in the generated + videos. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. + Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The generated videos. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; + /** A set of source input(s) for video generation. */ + source?: GenerateVideosSource; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** A set of source input(s) for video generation. */ +export declare interface GenerateVideosSource { + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly googleAuthOptions?; + private readonly project?; + private readonly location?; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Private method for generating images. + */ + private generateImagesInternal; + /** + * Private method for editing an image. + */ + private editImageInternal; + /** + * Private method for upscaling an image. + */ + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Private method for generating videos. + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** Used to override the default configuration. */ + config?: GetOperationConfig; + /** The operation to be retrieved. */ + operation: U; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** Whether to add a SynthID watermark to the generated images. */ + addWatermark?: boolean; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. */ + categories?: string[]; + /** List of scores of each categories. */ + scores?: number[]; + /** Internal use only. */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelTuningJobParameters): Promise; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoGenerationReferenceType, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosSource, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + Operation, + GenerateVideosOperation, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + CancelTuningJobConfig, + CancelTuningJobParameters, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationFromAPIResponseParameters, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + OperationGetParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example ``video/mp4``. */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. */ + referenceType?: VideoGenerationReferenceType; +} + +/** Enum for the reference type of a video generation reference image. */ +export declare enum VideoGenerationReferenceType { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + ASSET = "ASSET", + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + STYLE = "STYLE" +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs new file mode 100644 index 0000000..1a070a9 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs @@ -0,0 +1,18894 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +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 = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * 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"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + FunctionCallingConfigMode["VALIDATED"] = "VALIDATED"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the editing mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum for the reference type of a video generation reference image. */ +var VideoGenerationReferenceType; +(function (VideoGenerationReferenceType) { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + VideoGenerationReferenceType["ASSET"] = "ASSET"; + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + VideoGenerationReferenceType["STYLE"] = "STYLE"; +})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** A video generation operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (mcpToolSchema['outputSchema']) { + functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema']; + } + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +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, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + 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]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +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 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false 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; + } + return isValidContent(content); +} +function isValidContent(content) { + 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; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToMldev(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (parentObject !== undefined && fromVideo != null) { + setValueByPath(parentObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], generateVideosSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.17.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error('Source and prompt/image/video are mutually exclusive. Please only use source.'); + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelTuningJobParametersToMldev(params); + path = formatMap('{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserDownloader { + async download(_params, _apiClient) { + throw new Error('Download to file is not supported in the browser, please use a browser compliant download like an tag.'); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +class BrowserUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + return await uploadBlob(file, uploadUrl, apiClient); + } + async stat(file) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + else { + return await getBlobStat(file); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserWebSocketFactory { + create(url, headers, callbacks) { + return new BrowserWebSocket(url, headers, callbacks); + } +} +class BrowserWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new WebSocket(this.url); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error('An API Key must be set when running in a browser'); + } + // Web client only supports API key mode for Vertex AI. + if (options.project || options.location) { + throw new Error('Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.'); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, + /*vertexBaseUrlFromEnv*/ undefined, + /*geminiBaseUrlFromEnv*/ undefined); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web', + uploader: new BrowserUploader(), + downloader: new BrowserDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationReferenceType, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs.map b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs.map new file mode 100644 index 0000000..6c20b7c --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/web/_browser_downloader.ts","../../src/cross/_cross_uploader.ts","../../src/web/_browser_uploader.ts","../../src/web/_browser_websocket.ts","../../src/web/_web_auth.ts","../../src/web/web_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n /**\n * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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\".\n */\n VALIDATED = 'VALIDATED',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the editing mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum for the reference type of a video generation reference image. */\nexport enum VideoGenerationReferenceType {\n /**\n * A reference image that provides assets to the generated video,\n such as the scene, an object, a character, etc.\n */\n ASSET = 'ASSET',\n /**\n * A reference image that provides aesthetics including colors,\n lighting, texture, etc., to be used as the style of the generated video,\n such as 'anime', 'photography', 'origami', etc.\n */\n STYLE = 'STYLE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models). */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both. */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories. */\n categories?: string[];\n /** List of scores of each categories. */\n scores?: number[];\n /** Internal use only. */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data. */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response. */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content. */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled. */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True. */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images. */\n negativePrompt?: string;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality. */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model. */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response. */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response. */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt. */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images. */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** Whether to add a SynthID watermark to the generated images. */\n addWatermark?: boolean;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example ``video/mp4``. */\n mimeType?: string;\n}\n\n/** A set of source input(s) for video generation. */\nexport declare interface GenerateVideosSource {\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image. */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. */\n referenceType?: VideoGenerationReferenceType;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with\n unchanged inputs, the prediction results will be consistent. Otherwise,\n a random RNG seed will be used each time to produce a different\n result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and\n 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are\n supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific\n ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation\n progress. */\n pubsubTopic?: string;\n /** Explicitly state what should not be included in the generated\n videos. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos.\n Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos.\n Optional if image or video is provided. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. Not allowed if video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt is provided. Not allowed if image is provided. */\n video?: Video;\n /** A set of source input(s) for video generation. */\n source?: GenerateVideosSource;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The generated videos. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\nexport /** Optional parameters for tunings.get method. */\ndeclare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\n/** Optional parameters for tunings.cancel method. */\nexport declare interface CancelTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the cancel method. */\nexport declare interface CancelTuningJobParameters {\n /** The resource name of the tuning job. */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelTuningJobConfig;\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression. Only applicable if the\n ``output_mime_type`` is ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n /** The operation to be retrieved. */\n operation: U;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (mcpToolSchema['outputSchema']) {\n functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema'];\n }\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(\n fromObject: types.DeleteCachedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteCachedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.deleteCachedContentResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\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 }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(\n fromObject: types.DeleteFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteFileResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteFileResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToMldev(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(\n fromObject: types.GenerateVideosSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (parentObject !== undefined && fromVideo != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(\n fromObject: types.DeleteModelResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.17.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * source: {\n * prompt: 'A neon hologram of a cat driving at top speed',\n * },\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n if ((params.prompt || params.image || params.video) && params.source) {\n throw new Error(\n 'Source and prompt/image/video are mutually exclusive. Please only use source.',\n );\n }\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for generating images.\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Private method for editing an image.\n */\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for upscaling an image.\n */\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromVertex(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteModelResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteModelResponseFromMldev(apiResponse);\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Private method for generating videos.\n */\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function fetchPredictOperationParametersToMldev(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['operationName']) !== undefined) {\n throw new Error('operationName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['resourceName']) !== undefined) {\n throw new Error('resourceName parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToMldev(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cancelTuningJobParametersToVertex(\n fromObject: types.CancelTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Cancels a tuning job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelTuningJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nexport class BrowserDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw new Error(\n 'Download to file is not supported in the browser, please use a browser compliant download like an tag.',\n );\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {getBlobStat, uploadBlob} from '../cross/_cross_uploader.js';\nimport {File} from '../types.js';\n\nexport class BrowserUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n }\n\n return await uploadBlob(file, uploadUrl, apiClient);\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n } else {\n return await getBlobStat(file);\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\n\nexport class BrowserWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n return new BrowserWebSocket(url, headers, callbacks);\n }\n}\n\nexport class BrowserWebSocket implements Ws {\n private ws?: WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {BrowserDownloader} from './_browser_downloader.js';\nimport {BrowserUploader} from './_browser_uploader.js';\nimport {BrowserWebSocketFactory} from './_browser_websocket.js';\nimport {WebAuth} from './_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey}\n * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} should not be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error('An API Key must be set when running in a browser');\n }\n // Web client only supports API key mode for Vertex AI.\n if (options.project || options.location) {\n throw new Error(\n 'Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.',\n );\n }\n this.vertexai = options.vertexai ?? false;\n\n this.apiKey = options.apiKey;\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n /*vertexBaseUrlFromEnv*/ undefined,\n /*geminiBaseUrlFromEnv*/ undefined,\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web',\n uploader: new BrowserUploader(),\n downloader: new BrowserDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.cancelTuningJobParametersToVertex","converters.cancelTuningJobParametersToMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOperationFromMldev"],"mappings":"AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AAAM,aAAA;AACL,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AACF;IAED,OAAO,WAAW,CAAC,OAAO;AAC5B;;AC5EA;;;;AA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O,CAAC,IAAI,CAAC,SAAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/web.d.ts b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/web.d.ts new file mode 100644 index 0000000..f0ef33b --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/dist/web/web.d.ts @@ -0,0 +1,7726 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** Optional parameters for tunings.cancel method. */ +export declare interface CancelTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the cancel method. */ +export declare interface CancelTuningJobParameters { + /** The resource name of the tuning job. */ + name: string; + /** Optional parameters for the request. */ + config?: CancelTuningJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the editing mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", + /** + * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. 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". + */ + VALIDATED = "VALIDATED" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. */ + negativePrompt?: string; + /** Number of images to generate. */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with + unchanged inputs, the prediction results will be consistent. Otherwise, + a random RNG seed will be used each time to produce a different + result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and + 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are + supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific + ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation + progress. */ + pubsubTopic?: string; + /** Explicitly state what should not be included in the generated + videos. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. + Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The generated videos. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; + /** A set of source input(s) for video generation. */ + source?: GenerateVideosSource; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** A set of source input(s) for video generation. */ +export declare interface GenerateVideosSource { + /** The text prompt for generating the videos. + Optional if image or video is provided. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided. */ + video?: Video; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * source: { + * prompt: 'A neon hologram of a cat driving at top speed', + * }, + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Private method for generating images. + */ + private generateImagesInternal; + /** + * Private method for editing an image. + */ + private editImageInternal; + /** + * Private method for upscaling an image. + */ + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Private method for generating videos. + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** Used to override the default configuration. */ + config?: GetOperationConfig; + /** The operation to be retrieved. */ + operation: U; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** Whether to add a SynthID watermark to the generated images. */ + addWatermark?: boolean; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. */ + categories?: string[]; + /** List of scores of each categories. */ + scores?: number[]; + /** Internal use only. */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelTuningJobParameters): Promise; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoGenerationReferenceType, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosSource, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + Operation, + GenerateVideosOperation, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + CancelTuningJobConfig, + CancelTuningJobParameters, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationFromAPIResponseParameters, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + OperationGetParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example ``video/mp4``. */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. */ + referenceType?: VideoGenerationReferenceType; +} + +/** Enum for the reference type of a video generation reference image. */ +export declare enum VideoGenerationReferenceType { + /** + * A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc. + */ + ASSET = "ASSET", + /** + * A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc. + */ + STYLE = "STYLE" +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/node/package.json b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/node/package.json new file mode 100644 index 0000000..7666aff --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/node/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/node", + "main": "../dist/node/index.js" +} diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/package.json b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/package.json new file mode 100644 index 0000000..91ef791 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/package.json @@ -0,0 +1,129 @@ +{ + "name": "@google/genai", + "version": "1.17.0", + "description": "", + "type": "module", + "main": "dist/node/index.mjs", + "module": "dist/web/index.mjs", + "browser": "dist/web/index.mjs", + "typings": "dist/genai.d.ts", + "exports": { + ".": { + "browser": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "require": "./dist/node/index.cjs", + "default": "./dist/node/index.mjs" + }, + "types": "./dist/genai.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs", + "default": "./dist/index.mjs" + }, + "./web": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "./node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "default": "./dist/node/index.mjs" + } + }, + "scripts": { + "prepare": "npm run build-prod", + "build": "rollup -c && npm-run-all --parallel api-extractor:dev:* && node scripts/ignore_missing_mcp_dep.js", + "build-prod": "rollup -c && npm-run-all --parallel api-extractor:prod:* && node scripts/ignore_missing_mcp_dep.js", + "api-extractor:dev:main": "api-extractor run --local --verbose", + "api-extractor:dev:node": "api-extractor run -c api-extractor.node.json --local --verbose", + "api-extractor:dev:web": "api-extractor run -c api-extractor.web.json --local --verbose", + "api-extractor:prod:main": "api-extractor run --verbose", + "api-extractor:prod:node": "api-extractor run -c api-extractor.node.json --verbose", + "api-extractor:prod:web": "api-extractor run -c api-extractor.web.json --verbose", + "unit-test": "tsc && jasmine dist/test/unit/**/*_test.js dist/test/unit/*_test.js", + "system-test": "tsc && jasmine dist/test/system/**/*_test.js", + "test-server-tests": "tsc && GOOGLE_CLOUD_PROJECT=googcloudproj GOOGLE_CLOUD_LOCATION=googcloudloc jasmine dist/test/system/node/*_test.js -- --test-server", + "test-server-tests:record": "tsc && jasmine --fail-fast dist/test/system/node/*_test.js -- --test-server --record", + "docs": "typedoc && node --loader ts-node/esm scripts/add_docsite_license_headers.ts", + "pages-main": "node --loader ts-node/esm scripts/generate_pages.ts main", + "pages-release": "node --loader ts-node/esm scripts/generate_pages.ts release", + "format": "prettier '**/*.ts' '**/*.mjs' '**/*.json' --write", + "lint": "eslint '**/*.ts'", + "lint-fix": "eslint --fix '**/*.ts'", + "coverage-report": "./test/generate_report.sh" + }, + "engines": { + "node": ">=20.0.0" + }, + "files": [ + "dist/genai.d.ts", + "dist/index.mjs", + "dist/index.cjs", + "dist/index.mjs.map", + "dist/node/index.mjs", + "dist/node/index.cjs", + "dist/node/index.mjs.map", + "dist/node/node.d.ts", + "dist/web/index.mjs", + "dist/web/index.mjs.map", + "dist/web/web.d.ts", + "node/package.json", + "web/package.json" + ], + "devDependencies": { + "@eslint/js": "9.20.0", + "@microsoft/api-extractor": "^7.52.9", + "@rollup/plugin-json": "^6.1.0", + "@types/jasmine": "^5.1.2", + "@types/node": "^20.9.0", + "@types/unist": "^3.0.3", + "@types/ws": "^8.5.14", + "c8": "^10.1.3", + "eslint": "8.57.0", + "gts": "^5.2.0", + "jasmine": "^5.5.0", + "jasmine-reporters": "^2.4.0", + "npm-run-all": "^4.1.5", + "nyc": "^17.1.0", + "prettier": "3.3.3", + "prettier-plugin-organize-imports": "^4.1.0", + "rollup-plugin-typescript2": "^0.36.0", + "test-server-sdk": "^0.2.7", + "ts-node": "^10.9.2", + "tslib": "^2.8.1", + "tsx": "^4.19.4", + "typedoc": "^0.27.0", + "typescript": "~5.2.0", + "typescript-eslint": "8.24.1", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.22.4" + }, + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.11.4" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "https://github.com/googleapis/js-genai.git" + }, + "bugs": { + "url": "https://github.com/googleapis/js-genai/issues" + }, + "homepage": "https://github.com/googleapis/js-genai#readme", + "author": "", + "license": "Apache-2.0" +} diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/web/package.json b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/web/package.json new file mode 100644 index 0000000..606dd1f --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/@google/genai/web/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/web", + "module": "../dist/web/index.mjs" +} diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/google-auth-library b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/google-auth-library new file mode 120000 index 0000000..3f902cc --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/google-auth-library @@ -0,0 +1 @@ +../../google-auth-library@9.15.1/node_modules/google-auth-library \ No newline at end of file diff --git a/node_modules/.pnpm/@google+genai@1.17.0/node_modules/ws b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/ws new file mode 120000 index 0000000..f65be61 --- /dev/null +++ b/node_modules/.pnpm/@google+genai@1.17.0/node_modules/ws @@ -0,0 +1 @@ +../../ws@8.18.3/node_modules/ws \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +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. \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..e958e88 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..1de97d0 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/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GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;SAC/B;QACD,IAAI,QAAQ,GAAG,SAAS;YAAE,SAAS,GAAG,QAAQ,CAAC;KAChD;IAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;IACvC,QAAQ,SAAS;;;QAIf,kBAAkB;QAClB;YACE,OAAO,SAAS,CAAC;QAEnB,2BAA2B;;YAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..a783049 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..70a37f2 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path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,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..02a4c51 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +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. diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..b3e0708 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..532bab3 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,423 @@ +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +export { + decode, + decodeGeneratedRanges, + decodeOriginalScopes, + encode, + encodeGeneratedRanges, + encodeOriginalScopes +}; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..c276844 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/s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,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..2d8e459 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,464 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.sourcemapCodec = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module) { +"use strict"; +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); + +// src/sourcemap-codec.ts +var sourcemap_codec_exports = {}; +__export(sourcemap_codec_exports, { + decode: () => decode, + decodeGeneratedRanges: () => decodeGeneratedRanges, + decodeOriginalScopes: () => decodeOriginalScopes, + encode: () => encode, + encodeGeneratedRanges: () => encodeGeneratedRanges, + encodeOriginalScopes: () => encodeOriginalScopes +}); +module.exports = __toCommonJS(sourcemap_codec_exports); + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..abc18d2 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/sourcemap-codec.ts", "../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY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AAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..da55137 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,63 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.5", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "types/sourcemap-codec.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/sourcemap-codec.d.mts", + "default": "./dist/sourcemap-codec.mjs" + }, + "default": { + "types": "./types/sourcemap-codec.d.cts", + "default": "./dist/sourcemap-codec.umd.js" + } + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs sourcemap-codec.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/sourcemap-codec" + }, + "author": "Justin Ridgewell ", + "license": "MIT" +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts new file mode 100644 index 0000000..d194c2f --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts @@ -0,0 +1,345 @@ +import { StringReader, StringWriter } from './strings'; +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; + +const EMPTY: any[] = []; + +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; + +type Mix = (A & O) | (B & O); + +export type OriginalScope = Mix< + [Line, Column, Line, Column, Kind], + [Line, Column, Line, Column, Kind, Name], + { vars: Var[] } +>; + +export type GeneratedRange = Mix< + [Line, Column, Line, Column], + [Line, Column, Line, Column, SourcesIndex, ScopesIndex], + { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; + } +>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; + +export function decodeOriginalScopes(input: string): OriginalScope[] { + const { length } = input; + const reader = new StringReader(input); + const scopes: OriginalScope[] = []; + const stack: OriginalScope[] = []; + let line = 0; + + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + + if (!hasMoreVlq(reader, length)) { + const last = stack.pop()!; + last[2] = line; + last[3] = column; + continue; + } + + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + + const scope: OriginalScope = ( + hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind] + ) as OriginalScope; + + let vars: Var[] = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + + scopes.push(scope); + stack.push(scope); + } + + return scopes; +} + +export function encodeOriginalScopes(scopes: OriginalScope[]): string { + const writer = new StringWriter(); + + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + + return writer.flush(); +} + +function _encodeOriginalScopes( + scopes: OriginalScope[], + index: number, + writer: StringWriter, + state: [ + number, // GenColumn + ], +): number { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + + if (index > 0) writer.write(comma); + + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + + for (const v of vars) { + encodeInteger(writer, v, 0); + } + + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + + return index; +} + +export function decodeGeneratedRanges(input: string): GeneratedRange[] { + const { length } = input; + const reader = new StringReader(input); + const ranges: GeneratedRange[] = []; + const stack: GeneratedRange[] = []; + + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop()!; + last[2] = genLine; + last[3] = genColumn; + continue; + } + + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + + let callsite: CallSite | null = null; + let bindings: Binding[] = EMPTY; + let range: GeneratedRange; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0, + ); + + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange; + } else { + range = [genLine, genColumn, 0, 0] as GeneratedRange; + } + + range.isScope = !!hasScope; + + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0, + ); + + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges: BindingExpressionRange[]; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + + ranges.push(range); + stack.push(range); + } + + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + + return ranges; +} + +export function encodeGeneratedRanges(ranges: GeneratedRange[]): string { + if (ranges.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + + return writer.flush(); +} + +function _encodeGeneratedRanges( + ranges: GeneratedRange[], + index: number, + writer: StringWriter, + state: [ + number, // GenLine + number, // GenColumn + number, // DefSourcesIndex + number, // DefScopesIndex + number, // CallSourcesIndex + number, // CallLine + number, // CallColumn + ], +): number { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings, + } = range; + + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + + state[1] = encodeInteger(writer, range[1], state[1]); + + const fields = + (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn); + encodeInteger(writer, expRange[0]!, 0); + } + } + } + + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + + return index; +} + +function catchupLine(writer: StringWriter, lastLine: number, line: number) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..a81f894 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,111 @@ +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; +import { StringWriter, StringReader } from './strings'; + +export { + decodeOriginalScopes, + encodeOriginalScopes, + decodeGeneratedRanges, + encodeGeneratedRanges, +} from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +export function decode(mappings: string): SourceMapMappings { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded: SourceMapMappings = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + do { + const semi = reader.indexOf(';'); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + + while (reader.pos < semi) { + let seg: SourceMapSegment; + + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + + line.push(seg); + reader.pos++; + } + + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return decoded; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + + let genColumn = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + + genColumn = encodeInteger(writer, segment[0], genColumn); + + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + + return writer.flush(); +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/strings.ts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/strings.ts new file mode 100644 index 0000000..d161965 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/strings.ts @@ -0,0 +1,65 @@ +const bufLength = 1024 * 16; + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array): string { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array): string { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export class StringWriter { + pos = 0; + private out = ''; + private buffer = new Uint8Array(bufLength); + + write(v: number): void { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + + flush(): string { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} + +export class StringReader { + pos = 0; + declare private buffer: string; + + constructor(buffer: string) { + this.buffer = buffer; + } + + next(): number { + return this.buffer.charCodeAt(this.pos++); + } + + peek(): number { + return this.buffer.charCodeAt(this.pos); + } + + indexOf(char: string): number { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts new file mode 100644 index 0000000..a42c681 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts @@ -0,0 +1,55 @@ +import type { StringReader, StringWriter } from './strings'; + +export const comma = ','.charCodeAt(0); +export const semicolon = ';'.charCodeAt(0); + +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +export function decodeInteger(reader: StringReader, relative: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + return relative + value; +} + +export function encodeInteger(builder: StringWriter, num: number, relative: number): number { + let delta = num - relative; + + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + + return num; +} + +export function hasMoreVlq(reader: StringReader, max: number) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB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GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts new file mode 100644 index 0000000..5f35e22 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts new file mode 100644 index 0000000..199fb9f --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 0000000..dbd6602 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 0000000..2c739bc --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/resolve-uri b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/resolve-uri new file mode 120000 index 0000000..2414383 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/resolve-uri @@ -0,0 +1 @@ +../../../@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/sourcemap-codec b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/sourcemap-codec new file mode 120000 index 0000000..ab4324c --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/sourcemap-codec @@ -0,0 +1 @@ +../../../@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..37bb488 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +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. diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..8286cee --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,193 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { TraceMap, originalPositionFor, generatedPositionFor } from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + names: ['foo'], + mappings: 'KAyCIA', +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +trace-mapping: decoded JSON input x 183 ops/sec ±0.41% (87 runs sampled) +trace-mapping: encoded JSON input x 384 ops/sec ±0.89% (89 runs sampled) +trace-mapping: decoded Object input x 3,085 ops/sec ±0.24% (100 runs sampled) +trace-mapping: encoded Object input x 452 ops/sec ±0.80% (84 runs sampled) +source-map-js: encoded Object input x 88.82 ops/sec ±0.45% (77 runs sampled) +source-map-0.6.1: encoded Object input x 38.39 ops/sec ±1.88% (52 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 4,025,347 ops/sec ±0.15% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 3,333,136 ops/sec ±1.26% (90 runs sampled) +source-map-js: encoded originalPositionFor x 824,978 ops/sec ±1.06% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 741,300 ops/sec ±0.93% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,587,603 ops/sec ±0.75% (97 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +babel.min.js.map +trace-mapping: decoded JSON input x 17.43 ops/sec ±8.81% (33 runs sampled) +trace-mapping: encoded JSON input x 34.18 ops/sec ±4.67% (50 runs sampled) +trace-mapping: decoded Object input x 1,010 ops/sec ±0.41% (98 runs sampled) +trace-mapping: encoded Object input x 39.45 ops/sec ±4.01% (52 runs sampled) +source-map-js: encoded Object input x 6.57 ops/sec ±3.04% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±2.93% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,576,265 ops/sec ±0.74% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 5,019,743 ops/sec ±0.74% (94 runs sampled) +source-map-js: encoded originalPositionFor x 3,396,137 ops/sec ±42.32% (95 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,753,176 ops/sec ±0.72% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,423,633 ops/sec ±0.74% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +preact.js.map +trace-mapping: decoded JSON input x 3,499 ops/sec ±0.18% (98 runs sampled) +trace-mapping: encoded JSON input x 6,078 ops/sec ±0.25% (99 runs sampled) +trace-mapping: decoded Object input x 254,788 ops/sec ±0.13% (100 runs sampled) +trace-mapping: encoded Object input x 14,063 ops/sec ±0.27% (94 runs sampled) +source-map-js: encoded Object input x 2,465 ops/sec ±0.25% (98 runs sampled) +source-map-0.6.1: encoded Object input x 1,174 ops/sec ±1.90% (95 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 7,720,171 ops/sec ±0.14% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 6,864,485 ops/sec ±0.16% (101 runs sampled) +source-map-js: encoded originalPositionFor x 2,387,219 ops/sec ±0.28% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,565,339 ops/sec ±0.32% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 3,819,732 ops/sec ±0.38% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +*** + +react.js.map +trace-mapping: decoded JSON input x 1,719 ops/sec ±0.19% (99 runs sampled) +trace-mapping: encoded JSON input x 4,284 ops/sec ±0.51% (99 runs sampled) +trace-mapping: decoded Object input x 94,668 ops/sec ±0.08% (99 runs sampled) +trace-mapping: encoded Object input x 5,287 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded Object input x 814 ops/sec ±0.20% (98 runs sampled) +source-map-0.6.1: encoded Object input x 429 ops/sec ±0.24% (94 runs sampled) +Fastest is trace-mapping: decoded Object input + +trace-mapping: decoded originalPositionFor x 28,927,989 ops/sec ±0.61% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 27,394,475 ops/sec ±0.55% (97 runs sampled) +source-map-js: encoded originalPositionFor x 16,856,730 ops/sec ±0.45% (96 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,258,950 ops/sec ±0.41% (97 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 22,272,990 ops/sec ±0.58% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..8fce400 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,514 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +// Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of +// equal length to the sources. This is because the sources and sourcesContent are paired arrays, +// where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined +// sourcemap would desynchronize the sources/contents. +function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; +} + +const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, +}); +const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, +}); +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +let generatedPositionFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: decodedMappings(map), + }; + }; + encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: encodedMappings(map), + }; + }; +})(); +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..fec7769 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["bsFound"],"mappings":";;;SAEwB,OAAO,CAAC,KAAa,EAAE,IAAwB;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACjC;;ACTA;;;SAGwB,aAAa,CAAC,IAA+B;IACnE,IAAI,CAAC,IAAI;QAAE,OAAO,EAAE,CAAC;IACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC;;ACQO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC;;SClBb,SAAS,CAC/B,QAA8B,EAC9B,KAAc;IAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC3D,IAAI,aAAa,KAAK,QAAQ,CAAC,MAAM;QAAE,OAAO,QAAQ,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AG,CAAC,UAAU;YAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,cAAc,EAAE,GAAG,CAAC,cAAc;YAClC,QAAQ,EAAE,eAAe,CAAC,GAAG,CAAC;SAC/B,CAAC;KACH,CAAC;AACJ,CAAC,GAAA,CAAA;AAiBH,SAAS,oBAAoB,CAC3B,QAA+C,EAC/C,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAA4D;IAE5D,IAAI,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/D,IAAIA,KAAO,EAAE;QACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACzF;SAAM,IAAI,IAAI,KAAK,iBAAiB;QAAE,KAAK,EAAE,CAAC;IAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;AACzB;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..8b755bd --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,528 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri); + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri__default["default"](input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; i++, index++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; i--, index--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const { sections } = parsed; + let i = 0; + for (; i < sections.length - 1; i++) { + const no = sections[i + 1].offset; + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column); + } + if (sections.length > 0) { + addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity); + } + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) { + const map = AnyMap(section.map, mapUrl); + const { line: lineOffset, column: columnOffset } = section.offset; + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources } = map; + append(sources, resolvedSources); + append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length)); + append(names, map.names); + // If this section jumps forwards several lines, we need to add lines to the output mappings catch up. + for (let i = mappings.length; i <= lineOffset; i++) + mappings.push([]); + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. + const stopI = stopLine - lineOffset; + const len = Math.min(decoded.length, stopI + 1); + for (let i = 0; i < len; i++) { + const line = decoded[i]; + // On the 0th loop, the line will already exist due to a previous section, or the line catch up + // loop above. + const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (i === stopI && column >= stopColumn) + break; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + if (seg.length === 4) { + out.push([column, sourcesIndex, sourceLine, sourceColumn]); + continue; + } + out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of + // equal length to the sources. This is because the sources and sourcesContent are paired arrays, + // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined + // sourcemap would desynchronize the sources/contents. + function fillSourcesContent(len) { + const sourcesContent = []; + for (let i = 0; i < len; i++) + sourcesContent[i] = null; + return sourcesContent; + } + + const INVALID_ORIGINAL_MAPPING = Object.freeze({ + source: null, + line: null, + column: null, + name: null, + }); + const INVALID_GENERATED_MAPPING = Object.freeze({ + line: null, + column: null, + }); + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ + exports.generatedPositionFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + const isString = typeof map === 'string'; + if (!isString && map.constructor === TraceMap) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + if (sourceRoot || mapUrl) { + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + } + else { + this.resolvedSources = sources.map((s) => s || ''); + } + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return INVALID_ORIGINAL_MAPPING; + const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_ORIGINAL_MAPPING; + if (segment.length == 1) + return INVALID_ORIGINAL_MAPPING; + const { names, resolvedSources } = map; + return { + source: resolvedSources[segment[SOURCES_INDEX]], + line: segment[SOURCE_LINE] + 1, + column: segment[SOURCE_COLUMN], + name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + }; + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return INVALID_GENERATED_MAPPING; + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const memos = map._bySourceMemos; + const segments = generated[sourceIndex][line]; + if (segments == null) + return INVALID_GENERATED_MAPPING; + const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND); + if (segment == null) + return INVALID_GENERATED_MAPPING; + return { + line: segment[REV_GENERATED_LINE] + 1, + column: segment[REV_GENERATED_COLUMN], + }; + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const clone = Object.assign({}, map); + clone.mappings = []; + const tracer = new TraceMap(clone, mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.decodedMappings(map), + }; + }; + exports.encodedMap = (map) => { + return { + version: 3, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings: exports.encodedMappings(map), + }; + }; + })(); + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return null; + return segments[index]; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..4ef72e7 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../../src/resolve.ts","../../src/strip-filename.ts","../../src/sourcemap-segment.ts","../../src/sort.ts","../../src/binary-search.ts","../../src/by-source.ts","../../src/any-map.ts","../../src/trace-mapping.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["resolveUri","presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedPositionFor","eachMapping","decodedMap","encodedMap","encode","decode","bsFound"],"mappings":";;;;;;;;;;aAEwB,OAAO,CAAC,KAAa,EAAE,IAAwB;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;QAE7C,OAAOA,8BAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC;;ICTA;;;aAGwB,aAAa,CAAC,IAA+B;QACnE,IAAI,CAAC,IAAI;YAAE,OAAO,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK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AK,QAAQ,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..08bca6b --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +declare type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..88820e5 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export declare type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..8d1e538 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export declare type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d70924 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +declare type GeneratedLine = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..8cd4574 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,70 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMapInput, SectionedSourceMapInput, DecodedSourceMap, EncodedSourceMap, SectionedSourceMap, InvalidOriginalMapping, OriginalMapping as Mapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, EachMapping, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided + * the found mapping is from the same source and line as the originalPositionFor mapping. + * + * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1` + * using the same needle that would return `id` when calling `originalPositionFor`. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..2cc90c0 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,85 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export declare type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export declare type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export declare type GeneratedMapping = { + line: number; + column: number; +}; +export declare type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export declare type SourceMapInput = string | EncodedSourceMap | DecodedSourceMap | TraceMap; +export declare type SectionedSourceMapInput = SourceMapInput | SectionedSourceMap; +export declare type Needle = { + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: 1 | -1; +}; +export declare type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} diff --git a/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..a957780 --- /dev/null +++ b/node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,70 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.9", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "typings": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "ava debug", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 ava", + "test:watch": "ava --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "ava": "4.0.1", + "benchmark": "2.1.4", + "c8": "7.11.0", + "esbuild": "0.14.14", + "esbuild-node-loader": "0.6.4", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "typescript": "4.5.4" + }, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } +} diff --git a/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/LICENSE b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +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 diff --git a/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/README.md b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/README.md new file mode 100644 index 0000000..af0b6ef --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/README.md @@ -0,0 +1,38 @@ +### A base TSConfig for working with Node 10. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node10 +yarn add --dev @tsconfig/node10 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node10/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + + "compilerOptions": { + "lib": ["es2018"], + "module": "commonjs", + "target": "es2018", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node10.json). diff --git a/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/package.json b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/package.json new file mode 100644 index 0000000..1db1b6b --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/package.json @@ -0,0 +1,15 @@ +{ + "name": "@tsconfig/node10", + "repository": { + "type": "git", + "url": "https://github.com/tsconfig/bases.git", + "directory": "bases" + }, + "license": "MIT", + "description": "A base TSConfig for working with Node 10.", + "keywords": [ + "tsconfig", + "node10" + ], + "version": "1.0.11" +} \ No newline at end of file diff --git a/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/tsconfig.json b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/tsconfig.json new file mode 100644 index 0000000..b585482 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node10@1.0.11/node_modules/@tsconfig/node10/tsconfig.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + + "compilerOptions": { + "lib": ["es2018"], + "module": "commonjs", + "target": "es2018", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/LICENSE b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +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 diff --git a/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/README.md b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/README.md new file mode 100644 index 0000000..6352ccd --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 12. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node12 +yarn add --dev @tsconfig/node12 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node12/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 12", + + "compilerOptions": { + "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"], + "module": "commonjs", + "target": "es2019", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node12.json). diff --git a/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/package.json b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/package.json new file mode 100644 index 0000000..56aad61 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/package.json @@ -0,0 +1 @@ +{"name":"@tsconfig/node12","repository":{"type":"git","url":"https://github.com/tsconfig/bases.git","directory":"bases"},"license":"MIT","description":"A base TSConfig for working with Node 12.","keywords":["tsconfig","node12"],"version":"1.0.11"} \ No newline at end of file diff --git a/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/tsconfig.json b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/tsconfig.json new file mode 100644 index 0000000..eeaf944 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node12@1.0.11/node_modules/@tsconfig/node12/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 12", + + "compilerOptions": { + "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"], + "module": "commonjs", + "target": "es2019", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/LICENSE b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +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 diff --git a/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/README.md b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/README.md new file mode 100644 index 0000000..dad7f02 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 14. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node14 +yarn add --dev @tsconfig/node14 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node14/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 14", + + "compilerOptions": { + "lib": ["es2020"], + "module": "commonjs", + "target": "es2020", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node14.json). diff --git a/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/package.json b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/package.json new file mode 100644 index 0000000..742f97b --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/package.json @@ -0,0 +1 @@ +{"name":"@tsconfig/node14","repository":{"type":"git","url":"https://github.com/tsconfig/bases.git","directory":"bases"},"license":"MIT","description":"A base TSConfig for working with Node 14.","keywords":["tsconfig","node14"],"version":"1.0.3"} \ No newline at end of file diff --git a/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/tsconfig.json b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/tsconfig.json new file mode 100644 index 0000000..d1d7551 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node14@1.0.3/node_modules/@tsconfig/node14/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 14", + + "compilerOptions": { + "lib": ["es2020"], + "module": "commonjs", + "target": "es2020", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/LICENSE b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/LICENSE new file mode 100644 index 0000000..48ea661 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +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 diff --git a/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/README.md b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/README.md new file mode 100644 index 0000000..2946b2f --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/README.md @@ -0,0 +1,40 @@ +### A base TSConfig for working with Node 16. + +Add the package to your `"devDependencies"`: + +```sh +npm install --save-dev @tsconfig/node16 +yarn add --dev @tsconfig/node16 +``` + +Add to your `tsconfig.json`: + +```json +"extends": "@tsconfig/node16/tsconfig.json" +``` + +--- + +The `tsconfig.json`: + +```jsonc +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 16", + + "compilerOptions": { + "lib": ["es2021"], + "module": "Node16", + "target": "es2021", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} + +``` + +You can find the [code here](https://github.com/tsconfig/bases/blob/master/bases/node16.json). diff --git a/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/package.json b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/package.json new file mode 100644 index 0000000..8ccc97f --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/package.json @@ -0,0 +1,15 @@ +{ + "name": "@tsconfig/node16", + "repository": { + "type": "git", + "url": "https://github.com/tsconfig/bases.git", + "directory": "bases" + }, + "license": "MIT", + "description": "A base TSConfig for working with Node 16.", + "keywords": [ + "tsconfig", + "node16" + ], + "version": "1.0.4" +} \ No newline at end of file diff --git a/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/tsconfig.json b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/tsconfig.json new file mode 100644 index 0000000..2671912 --- /dev/null +++ b/node_modules/.pnpm/@tsconfig+node16@1.0.4/node_modules/@tsconfig/node16/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Node 16", + + "compilerOptions": { + "lib": ["es2021"], + "module": "Node16", + "target": "es2021", + + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node" + } +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/LICENSE b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/README.md b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/README.md new file mode 100644 index 0000000..0986406 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Thu, 04 Sep 2025 10:02:38 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..b79fc21 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1056 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls(fn: undefined, exact?: number): () => void; + calls any>(fn: Func, exact?: number): Func; + calls any>(fn?: Func, exact?: number): Func | (() => void); + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + | "AssertionError" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + AssertionError: typeof AssertionError; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert/strict.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/async_hooks.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..2377689 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,623 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.buffer.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000..b22f83a --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,463 @@ +declare module "buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + type NonSharedBuffer = Buffer; + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..cbdf207 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1930 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/child_process.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..6a12a8c --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1453 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js) + */ +declare module "child_process" { + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v24.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/cluster.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..fa25fda --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,579 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker | undefined; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/compatibility/iterators.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000..156e785 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/console.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..c923bd0 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/constants.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..5685a9d --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/constants.d.ts @@ -0,0 +1,21 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/crypto.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..e3c7d67 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4532 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v24.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` + * (for Diffie-Hellman), `'ec'`, `'x448'`, or `'x25519'` (for ECDH). + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: Buffer) => void, + ): void; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v24.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dgram.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..35239f9 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,599 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..fa5ed69 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,578 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..f7539fd --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns.d.ts @@ -0,0 +1,918 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v24.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + export interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + export function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v24.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns/promises.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..efb9fbf --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/domain.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..4c64115 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/events.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..b79141f --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/events.d.ts @@ -0,0 +1,930 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + } + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` 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 `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..5f3bd7a --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4440 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | undefined | null; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadSyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs/promises.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..d3386aa --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1277 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: FileReadOptions, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..af46ec1 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.d.ts @@ -0,0 +1,168 @@ +declare var global: typeof globalThis; + +declare var process: NodeJS.Process; +declare var console: Console; + +interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; +} + +/** + * Enable this API with the `--expose-gc` CLI flag. + */ +declare var gc: NodeJS.GCFunction | undefined; + +declare namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.typedarray.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000..6d5c952 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,22 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + } +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..4df8fad --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http.d.ts @@ -0,0 +1,2046 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v24.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). + * @since v22.5.0 + */ + const WebSocket: import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http2.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..5e53de7 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2630 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + /** @deprecated */ + sumDependencyWeight?: number | undefined; + /** @deprecated */ + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * @deprecated Priority signaling is no longer supported in Node.js. + */ + priority(options: unknown): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: Pick, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "connect", + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + export interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + export interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/https.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..a40f06b --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/https.d.ts @@ -0,0 +1,545 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/index.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..6c48c80 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/index.d.ts @@ -0,0 +1,99 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/inspector.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..06333e4 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,4211 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable', callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable', callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: 'Network.getRequestPostData', callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: 'Network.getResponseBody', callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: 'Network.streamResourceContent', + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: 'Network.streamResourceContent', callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + class Session extends EventEmitter { + /** + * Create a new instance of the `inspector.Session` class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable'): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable'): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: 'Network.streamResourceContent', params?: Network.StreamResourceContentParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/module.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..c0c85f9 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/module.d.ts @@ -0,0 +1,893 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * If `cacheDir` is not specified, Node.js will either use the directory specified by the + * `NODE_COMPILE_CACHE=dir` environment variable if it's set, or use + * `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's + * recommended to call `module.enableCompileCache()` without specifying the `cacheDir`, + * so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment + * variable when necessary. + * + * Since compile cache is supposed to be a quiet optimization that is not required for the + * application to be functional, this method is designed to not throw any exception when the + * compile cache cannot be enabled. Instead, it will return an object containing an error + * message in the `message` field to aid debugging. + * If compile cache is enabled successfully, the `directory` field in the returned object + * contains the path to the directory where the compile cache is stored. The `status` + * field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param cacheDir Optional path to specify the directory where the compile cache + * will be stored/retrieved. + */ + function enableCompileCache(cacheDir?: string): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v24.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v24.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v24.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v24.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v24.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = + | "addon" + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + /** + * The `initialize` hook provides a way to define a custom function that runs in + * the hooks thread when the hooks module is initialized. Initialization happens + * when the hooks module is registered via {@link register}. + * + * This hook can receive data from a {@link register} invocation, including + * ports and other transferable objects. The return value of `initialize` can be a + * `Promise`, in which case it will be awaited before the main application thread + * execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored); can be an intermediary value. + */ + format?: string | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for telling Node.js where to find and + * how to cache a given `import` statement or expression, or `require` call. It can + * optionally return a format (such as `'module'`) as a hint to the `load` hook. If + * a format is specified, the `load` hook is ultimately responsible for providing + * the final `format` value (and it is free to ignore the hint provided by + * `resolve`); if `resolve` provides a `format`, a custom `load` hook is required + * even if only to pass the value to the Node.js default `load` hook. + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain (can be an intermediary value). + */ + format: string | null | undefined; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource | undefined; + } + /** + * The `load` hook provides a way to define a custom method of determining how a + * URL should be interpreted, retrieved, and parsed. It is also in charge of + * validating the import attributes. + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v23.7.0, v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v23.7.0, v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + interface ImportMeta { + /** + * The directory name of the current module. + * + * This is the same as the `path.dirname()` of the `import.meta.filename`. + * + * > **Caveat**: only present on `file:` modules. + * @since v21.2.0, v20.11.0 + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with + * symlinks resolved. + * + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * + * > **Caveat** only local modules support this property. Modules not using the + * > `file:` protocol will not provide it. + * @since v21.2.0, v20.11.0 + */ + filename: string; + /** + * The absolute `file:` URL of the module. + * + * This is defined exactly the same as it is in browsers providing the URL of the + * current module file. + * + * This enables useful patterns such as relative file loading: + * + * ```js + * import { readFileSync } from 'node:fs'; + * const buffer = readFileSync(new URL('./data.proto', import.meta.url)); + * ``` + */ + url: string; + /** + * `import.meta.resolve` is a module-relative resolution function scoped to + * each module, returning the URL string. + * + * ```js + * const dependencyAsset = import.meta.resolve('component-lib/asset.css'); + * // file:///app/node_modules/component-lib/asset.css + * import.meta.resolve('./dep.js'); + * // file:///app/dep.js + * ``` + * + * All features of the Node.js module resolution are supported. Dependency + * resolutions are subject to the permitted exports resolutions within the package. + * + * **Caveats**: + * + * * This can result in synchronous file-system operations, which + * can impact performance similarly to `require.resolve`. + * * This feature is not available within custom loaders (it would + * create a deadlock). + * @since v13.9.0, v12.16.0 + * @param specifier The module specifier to resolve relative to the + * current module. + * @param parent An optional absolute parent module URL to resolve from. + * **Default:** `import.meta.url` + * @returns The absolute URL string that the specifier would resolve to. + */ + resolve(specifier: string, parent?: string | URL): string; + /** + * `true` when the current module is the entry point of the current process; `false` otherwise. + * + * Equivalent to `require.main === module` in CommonJS. + * + * Analogous to Python's `__name__ == "__main__"`. + * + * ```js + * export function foo() { + * return 'Hello, world'; + * } + * + * function main() { + * const message = foo(); + * console.log(message); + * } + * + * if (import.meta.main) main(); + * // `foo` can be imported from another module without possible side-effects from `main` + * ``` + * @since v24.2.0 + * @experimental + */ + main: boolean; + } + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v24.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v24.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + // TODO: consider removing in a future major version update + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/net.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..7a4c5cb --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/net.d.ts @@ -0,0 +1,1032 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + blockList?: BlockList | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/os.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..77a6336 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/os.d.ts @@ -0,0 +1,496 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, + * `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v24.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): NodeJS.Architecture; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, + * `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/package.json b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/package.json new file mode 100644 index 0000000..7486ae8 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/package.json @@ -0,0 +1,155 @@ +{ + "name": "@types/node", + "version": "24.3.1", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + }, + { + "name": "Yagiz Nizipli", + "githubUsername": "anonrig", + "url": "https://github.com/anonrig" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + }, + "<=5.7": { + "*": [ + "ts5.7/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~7.10.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "178c30a76a74f3afb6f7d4e412cd6957c2fb4bb51e6666143a72508c73a154c7", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/path.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..d363397 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/perf_hooks.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..51d78d0 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,984 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/process.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..7428b36 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/process.d.ts @@ -0,0 +1,2073 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v24.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v24.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v24.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v24.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/punycode.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..7ac26c8 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/querystring.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..aaeefe8 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..519b4a4 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline.d.ts @@ -0,0 +1,594 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter implements Disposable { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v24.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline/promises.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..c0ebf4b --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/repl.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..60dc94a --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/repl.d.ts @@ -0,0 +1,438 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + interface REPLServerSetupHistoryOptions { + filePath?: string | undefined; + size?: number | undefined; + removeHistoryDuplicates?: boolean | undefined; + onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, a pipe `'|'` is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void; + setupHistory( + historyConfig?: REPLServerSetupHistoryOptions, + callback?: (err: Error | null, repl: this) => void, + ): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sea.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..5119ede --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sqlite.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..9019832 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,687 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | Uint8Array; + /** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */ + type SupportedValueType = SQLOutputValue; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): Uint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): Uint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * Callback function that will be called with the number of pages copied and the total number of + * pages. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that resolves when the backup is completed and rejects if an error occurs. + */ + function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + } +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..b586dd2 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1668 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v24.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v24.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class Stream extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace Stream { + export { Stream, streamPromises as promises }; + } + namespace Stream { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: T, size: number): void; + } + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: Readable, + options?: { + strategy?: streamWeb.QueuingStrategy | undefined; + }, + ): streamWeb.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v24.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v24.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * @returns `AsyncIterator` to fully consume the stream. + * @since v10.0.0 + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: T, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: T, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Calls `writable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v22.4.0, v20.16.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?(this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: T, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + } + export = Stream; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/consumers.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..746d6e5 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/promises.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..d54c14c --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/web.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..881e29c --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,622 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/string_decoder.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..3632c16 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/test.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..d397dba --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/test.d.ts @@ -0,0 +1,2334 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v24.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: "test:watch:restarted", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: "test:watch:restarted"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: "test:watch:restarted", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: "test:watch:restarted", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: "test:watch:restarted", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: "test:watch:restarted", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends + Pick< + typeof import("assert"), + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws" + > + { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..30a91c0 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers.d.ts @@ -0,0 +1,285 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers/promises.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..7ad2b29 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers/promises.js) + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tls.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..b9c4f24 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1213 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/trace_events.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..56e4620 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v24.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v24.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000..d19026d --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,460 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + type NonSharedBuffer = Buffer; + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts new file mode 100644 index 0000000..f148cc4 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts @@ -0,0 +1,71 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS <=5.6. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array extends Pick { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: ArrayBufferLike; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: Float16Array) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: (value: number, index: number, array: Float16Array) => unknown, + thisArg?: any, + ): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reverse(): Float16Array; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): Float16Array; + with(index: number, value: number): Float16Array; + [index: number]: number; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000..255e204 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,20 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + } +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/index.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000..47c03b5 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,101 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts new file mode 100644 index 0000000..110b1eb --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts @@ -0,0 +1,72 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS 5.7. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: TArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + entries(): ArrayIterator<[number, number]>; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: this) => value is S, + thisArg?: any, + ): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + keys(): ArrayIterator; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reverse(): this; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): this; + values(): ArrayIterator; + with(index: number, value: number): Float16Array; + [Symbol.iterator](): ArrayIterator; + [index: number]: number; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/index.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000..b23e5d4 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,101 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js 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. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tty.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..602324a --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/url.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..83e3872 --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/url.d.ts @@ -0,0 +1,1025 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): Buffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. + * Returns `null` if `input` is not a valid. + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + * @since v22.1.0 + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + /** + * @since v23.8.0 + * @experimental + */ + class URLPattern { + constructor(input: string | URLPatternInit, baseURL: string, options?: URLPatternOptions); + constructor(input?: string | URLPatternInit, options?: URLPatternOptions); + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + readonly username: string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { + URL as _URL, + URLPattern as _URLPattern, + URLPatternInit as _URLPatternInit, + URLPatternResult as _URLPatternResult, + URLSearchParams as _URLSearchParams, + } from "url"; + global { + interface URL extends _URL {} + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + interface URLSearchParams extends _URLSearchParams {} + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + interface URLPatternInit extends _URLPatternInit {} + interface URLPatternResult extends _URLPatternResult {} + interface URLPattern extends _URLPattern {} + var URLPattern: typeof _URLPattern; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/util.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..142e78b --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/util.d.ts @@ -0,0 +1,2309 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.column}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v24.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "none" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + options?: StyleTextOptions, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default value to + * be used if (and only if) the option does not appear in the arguments to be + * parsed. It must be of the same type as the `type` property. When `multiple` + * is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v24.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array) instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v24.0.0 + */ + function isFloat16Array(object: unknown): object is Float16Array; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + * @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead. + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/v8.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..8d9af4e --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/v8.d.ts @@ -0,0 +1,919 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/vm.d.ts b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..bba2e0b --- /dev/null +++ b/node_modules/.pnpm/@types+node@24.3.1/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1036 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: "source" | "evaluation", + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader + +``` + +Open the above .html file in a browser and you should see + +Node Example + +**[Full online demo](http://kpdecker.github.com/jsdiff)** + +## Compatibility + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) + +jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. + +## License + +See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.js new file mode 100644 index 0000000..03571ca --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.js @@ -0,0 +1,1585 @@ +/*! + + diff v4.0.1 + +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +@license +*/ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.Diff = {})); +}(this, function (exports) { 'use strict'; + + function Diff() {} + Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } + + var characterDiff = new Diff(); + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } + + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = new Diff(); + + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + var lineDiff = new Diff(); + + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } + + var sentenceDiff = new Diff(); + + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + var cssDiff = new Diff(); + + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } + } + + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); + } + + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = lineDiff.tokenize; + + jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + + jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } + + var arrayDiff = new Diff(); + + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } + + // Iterator that traverses in the range of [min, max], stepping + // by distance from a given start position. I.e. for [0, 4], with + // start of 2, this will iterate 2, 3, 1, 4, 0. + function distanceIterator (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; + } + + function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } + + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; + + // Mine inserted + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; + + // Theirs inserted + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; + } + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } + + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; + } + + /* See LICENSE file for terms of use */ + + exports.Diff = Diff; + exports.diffChars = diffChars; + exports.diffWords = diffWords; + exports.diffWordsWithSpace = diffWordsWithSpace; + exports.diffLines = diffLines; + exports.diffTrimmedLines = diffTrimmedLines; + exports.diffSentences = diffSentences; + exports.diffCss = diffCss; + exports.diffJson = diffJson; + exports.diffArrays = diffArrays; + exports.structuredPatch = structuredPatch; + exports.createTwoFilesPatch = createTwoFilesPatch; + exports.createPatch = createPatch; + exports.applyPatch = applyPatch; + exports.applyPatches = applyPatches; + exports.parsePatch = parsePatch; + exports.merge = merge; + exports.convertChangesToDMP = convertChangesToDMP; + exports.convertChangesToXML = convertChangesToXML; + exports.canonicalize = canonicalize; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.min.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.min.js new file mode 100644 index 0000000..976ad93 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/dist/diff.min.js @@ -0,0 +1,38 @@ +/*! + + diff v4.0.1 + +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +@license +*/ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).Diff={})}(this,function(e){"use strict";function t(){}function g(e,n,t,r,i){for(var o=0,s=n.length,l=0,a=0;oe.length?t:e}),u.value=e.join(d)}else u.value=e.join(t.slice(l,l+u.count));l+=u.count,u.added||(a+=u.count)}}var c=n[s-1];return 1=c&&h<=r+1)return d([{value:this.join(u),count:u.length}]);function i(){for(var e=-1*p;e<=p;e+=2){var n=void 0,t=v[e-1],r=v[e+1],i=(r?r.newPos:0)-e;t&&(v[e-1]=void 0);var o=t&&t.newPos+1=c&&h<=i+1)return d(g(f,n.components,u,a,f.useLongestToken));v[e]=n}else v[e]=void 0}var l;p++}if(n)!function e(){setTimeout(function(){if(t=v.length-2&&t.length<=p.context){var u=/\n$/.test(c),f=/\n$/.test(h),d=0==t.length&&x.length>a.oldLines;!u&&d&&x.splice(a.oldLines,0,"\\ No newline at end of file"),(u||d)&&f||x.push("\\ No newline at end of file")}m.push(a),y=w=0,x=[]}L+=t.length,S+=t.length}},o=0;oe.length)return!1;for(var t=0;t"):r.removed&&n.push(""),n.push((i=r.value,void 0,i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""))),r.added?n.push(""):r.removed&&n.push("")}var i;return n.join("")},e.canonicalize=v,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/dmp.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/dmp.js new file mode 100644 index 0000000..91ff40a --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/dmp.js @@ -0,0 +1,32 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.convertChangesToDMP = convertChangesToDMP; + +/*istanbul ignore end*/ +// See: http://code.google.com/p/google-diff-match-patch/wiki/API +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWO0FBQUEsTUFDSUMsTUFESjtBQUFBLE1BRUlDLFNBRko7O0FBR0EsT0FBSyxJQU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GVyYXRpb24gPSAwO1xuICAgIH1cblxuICAgIHJldC5wdXNoKFtvcGVyYXRpb24sIGNoYW5nZS52YWx1ZV0pO1xuICB9XG4gIHJldHVybiByZXQ7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/xml.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/xml.js new file mode 100644 index 0000000..69ec60c --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/convert/xml.js @@ -0,0 +1,42 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.convertChangesToXML = convertChangesToXML; + +/*istanbul ignore end*/ +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWOztBQUNBLE9BQUssSUFBSUMsQ0F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diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/array.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/array.js new file mode 100644 index 0000000..81f42ea --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/array.js @@ -0,0 +1,45 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffArrays = diffArrays; +exports.arrayDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var arrayDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.arrayDiff = arrayDiff; + +/*istanbul ignore end*/ +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJkaWZmQXJyYXlzIiwib2xkQXJyIiwibmV3QXJyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxTQUFTLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBSjtBQUFBLEVBQWxCOzs7Ozs7QUFDUEQsU0FBUyxDQUFDRSxRQUFWLEdBQXFCLFVBQVNDLEtBQVQsRUFBZ0I7QUFDbkMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLEVBQVA7QUFDRCxDQUZEOztBQUdBSixTQUFTLENBQUNLLElBQVYsR0FBaUJMLFNBQVMsQ0FBQ00sV0FBVixHQUF3QixVQUFTSCxLQUFULEVBQWdCO0FBQ3ZELFNBQU9BLEtBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNJLFVBQVQsQ0FBb0JDLE1BQXBCLEVBQTRCQyxNQUE1QixFQUFvQ0MsUUFBcEMsRUFBOEM7QUFBRSxTQUFPVixTQUFTLENBQUNXLElBQVYsQ0FBZUgsTUFBZixFQUF1QkMsTUFBdkIsRUFBK0JDLFFBQS9CLENBQVA7QUFBa0QiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgYXJyYXlEaWZmID0gbmV3IERpZmYoKTtcbmFycmF5RGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zbGljZSgpO1xufTtcbmFycmF5RGlmZi5qb2luID0gYXJyYXlEaWZmLnJlbW92ZUVtcHR5ID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZBcnJheXMob2xkQXJyLCBuZXdBcnIsIGNhbGxiYWNrKSB7IHJldHVybiBhcnJheURpZmYuZGlmZihvbGRBcnIsIG5ld0FyciwgY2FsbGJhY2spOyB9XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/base.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/base.js new file mode 100644 index 0000000..ea661fe --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/base.js @@ -0,0 +1,304 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = Diff; + +/*istanbul ignore end*/ +function Diff() {} + +Diff.prototype = { + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + diff: function diff(oldString, newString) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = + /*istanbul ignore start*/ + void 0 + /*istanbul ignore end*/ + ; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + castInput: function castInput(value) { + return value; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + tokenize: function tokenize(value) { + return value.split(''); + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Jhc2UuanMiXSwibmFtZXMiOlsiRGlmZiIsInByb3RvdHlwZSIsImRpZmYiLCJvbGRTdHJpbmciLCJuZXdTdHJpbmciLCJvcHRpb25zIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwic2V0VGltZW91dCIsInVuZGVmaW5lZCIsImNhc3RJbnB1dCIsInJlbW92ZUVtcHR5IiwidG9rZW5pemUiLCJuZXdMZW4iLCJsZW5ndGgiLCJvbGRMZW4iLCJlZGl0TGVuZ3RoIiwibWF4RWRpdExlbmd0aCIsImJlc3RQYXRoIiwibmV3UG9zIiwiY29tcG9uZW50cyIsIm9sZFBvcyIsImV4dHJhY3RDb21tb24iLCJqb2luIiwiY291bnQiLCJleGVjRWRpdExlbmd0aCIsImRpYWdvbmFsUGF0aCIsImJhc2VQYXRoIiwiYWRkUGF0aCIsInJlbW92ZVBhdGgiLCJjYW5BZGQiLCJjYW5SZW1vdmUiLCJjbG9uZVBhdGgiLCJwdXNoQ29tcG9uZW50IiwiYnVpbGRWYWx1ZXMiLCJ1c2VMb25nZXN0VG9rZW4iLCJleGVjIiwicmV0IiwiYWRkZWQiLCJyZW1vdmVkIiwibGFzdCIsInB1c2giLCJjb21tb25Db3VudCIsImVxdWFscyIsImxlZnQiLCJyaWdodCIsImNvbXBhcmF0b3IiLCJpZ25vcmVDYXNlIiwidG9Mb3dlckNhc2UiLCJhcnJheSIsImkiLCJzcGxpdCIsImNoYXJzIiwiY29tcG9uZW50UG9zIiwiY29tcG9uZW50TGVuIiwiY29tcG9uZW50Iiwic2xpY2UiLCJtYXAiLCJvbGRWYWx1ZSIsInRtcCIsImxhc3RDb21wb25lbnQiLCJwb3AiLCJw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oYW5kbGUgZm9yIHdoZW4gb25lIHRlcm1pbmFsIGlzIGlnbm9yZWQgKGkuZS4gd2hpdGVzcGFjZSkuXG4gIC8vIEZvciB0aGlzIGNhc2Ugd2UgbWVyZ2UgdGhlIHRlcm1pbmFsIGludG8gdGhlIHByaW9yIHN0cmluZyBhbmQgZHJvcCB0aGUgY2hhbmdlLlxuICAvLyBUaGlzIGlzIG9ubHkgYXZhaWxhYmxlIGZvciBzdHJpbmcgbW9kZS5cbiAgbGV0IGxhc3RDb21wb25lbnQgPSBjb21wb25lbnRzW2NvbXBvbmVudExlbiAtIDFdO1xuICBpZiAoY29tcG9uZW50TGVuID4gMVxuICAgICAgJiYgdHlwZW9mIGxhc3RDb21wb25lbnQudmFsdWUgPT09ICdzdHJpbmcnXG4gICAgICAmJiAobGFzdENvbXBvbmVudC5hZGRlZCB8fCBsYXN0Q29tcG9uZW50LnJlbW92ZWQpXG4gICAgICAmJiBkaWZmLmVxdWFscygnJywgbGFzdENvbXBvbmVudC52YWx1ZSkpIHtcbiAgICBjb21wb25lbnRzW2NvbXBvbmVudExlbiAtIDJdLnZhbHVlICs9IGxhc3RDb21wb25lbnQudmFsdWU7XG4gICAgY29tcG9uZW50cy5wb3AoKTtcbiAgfVxuXG4gIHJldHVybiBjb21wb25lbnRzO1xufVxuXG5mdW5jdGlvbiBjbG9uZVBhdGgocGF0aCkge1xuICByZXR1cm4geyBuZXdQb3M6IHBhdGgubmV3UG9zLCBjb21wb25lbnRzOiBwYXRoLmNvbXBvbmVudHMuc2xpY2UoMCkgfTtcbn1cbiJdfQ== diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/character.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/character.js new file mode 100644 index 0000000..4722b16 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/character.js @@ -0,0 +1,37 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffChars = diffChars; +exports.characterDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var characterDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.characterDiff = characterDiff; + +/*istanbul ignore end*/ +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJjaGFyYWN0ZXJEaWZmIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxhQUFhLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBSjtBQUFBLEVBQXRCOzs7Ozs7QUFDQSxTQUFTQyxTQUFULENBQW1CQyxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLEVBQTRDO0FBQUUsU0FBT0wsYUFBYSxDQUFDTSxJQUFkLENBQW1CSCxNQUFuQixFQUEyQkMsTUFBM0IsRUFBbUNDLE9BQW5DLENBQVA7QUFBcUQiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgY2hhcmFjdGVyRGlmZiA9IG5ldyBEaWZmKCk7XG5leHBvcnQgZnVuY3Rpb24gZGlmZkNoYXJzKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKSB7IHJldHVybiBjaGFyYWN0ZXJEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpOyB9XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/css.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/css.js new file mode 100644 index 0000000..69ba47e --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/css.js @@ -0,0 +1,41 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffCss = diffCss; +exports.cssDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var cssDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.cssDiff = cssDiff; + +/*istanbul ignore end*/ +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJjc3NEaWZmIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7OztBQUVPLElBQU1BLE9BQU8sR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFKO0FBQUEsRUFBaEI7Ozs7OztBQUNQRCxPQUFPLENBQUNFLFFBQVIsR0FBbUIsVUFBU0MsS0FBVCxFQUFnQjtBQUNqQyxTQUFPQSxLQUFLLENBQUNDLEtBQU4sQ0FBWSxlQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNDLE9BQVQsQ0FBaUJDLE1BQWpCLEVBQXlCQyxNQUF6QixFQUFpQ0MsUUFBakMsRUFBMkM7QUFBRSxTQUFPUixPQUFPLENBQUNTLElBQVIsQ0FBYUgsTUFBYixFQUFxQkMsTUFBckIsRUFBNkJDLFFBQTdCLENBQVA7QUFBZ0QiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgY3NzRGlmZiA9IG5ldyBEaWZmKCk7XG5jc3NEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNwbGl0KC8oW3t9OjssXXxcXHMrKS8pO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDc3Mob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7IHJldHVybiBjc3NEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuIl19 diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/json.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/json.js new file mode 100644 index 0000000..715ef08 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/json.js @@ -0,0 +1,163 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffJson = diffJson; +exports.canonicalize = canonicalize; +exports.jsonDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_line = require("./line") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/*istanbul ignore end*/ +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +/*istanbul ignore start*/ +exports.jsonDiff = jsonDiff; + +/*istanbul ignore end*/ +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = +/*istanbul ignore start*/ +_line +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +lineDiff +/*istanbul ignore end*/ +.tokenize; + +jsonDiff.castInput = function (value) { + /*istanbul ignore start*/ + var _this$options = + /*istanbul ignore end*/ + this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + typeof v === 'undefined' ? undefinedReplacement : v + ); + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return ( + /*istanbul ignore start*/ + _base + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + default + /*istanbul ignore end*/ + .prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( + /*istanbul ignore start*/ + _typeof( + /*istanbul ignore end*/ + obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsib2JqZWN0UHJvdG90eXBlVG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImpzb25EaWZmIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2Vua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tcbiAgICBzdGFjay5wdXNoKG9iaik7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IHt9O1xuICAgIHJlcGxhY2VtZW50U3RhY2sucHVzaChjYW5vbmljYWxpemVkT2JqKTtcbiAgICBsZXQgc29ydGVkS2V5cyA9IFtdLFxuICAgICAgICBrZXk7XG4gICAgZm9yIChrZXkgaW4gb2JqKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/line.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/line.js new file mode 100644 index 0000000..f323f84 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/line.js @@ -0,0 +1,89 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffLines = diffLines; +exports.diffTrimmedLines = diffTrimmedLines; +exports.lineDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_params = require("../util/params") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var lineDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.lineDiff = lineDiff; + +/*istanbul ignore end*/ +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} + +function diffTrimmedLines(oldStr, newStr, callback) { + var options = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _params + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsibGluZURpZmYiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInJldExpbmVzIiwibGluZXNBbmROZXdsaW5lcyIsInNwbGl0IiwibGVuZ3RoIiwicG9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ZXhwb3J0IGZ1bmN0aW9uIGRpZmZUcmltbWVkTGluZXMob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7XG4gIGxldCBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKGNhbGxiYWNrLCB7aWdub3JlV2hpdGVzcGFjZTogdHJ1ZX0pO1xuICByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/sentence.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/sentence.js new file mode 100644 index 0000000..9ee96e9 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/sentence.js @@ -0,0 +1,41 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffSentences = diffSentences; +exports.sentenceDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +var sentenceDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.sentenceDiff = sentenceDiff; + +/*istanbul ignore end*/ +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbInNlbnRlbmNlRGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVl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.2/node_modules/diff/lib/diff/word.js new file mode 100644 index 0000000..0b952e0 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/diff/word.js @@ -0,0 +1,107 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.diffWords = diffWords; +exports.diffWordsWithSpace = diffWordsWithSpace; +exports.wordDiff = void 0; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_params = require("../util/params") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new +/*istanbul ignore start*/ +_base +/*istanbul ignore end*/ +. +/*istanbul ignore start*/ +default +/*istanbul ignore end*/ +(); + +/*istanbul ignore start*/ +exports.wordDiff = wordDiff; + +/*istanbul ignore end*/ +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _params + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} + +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsIkRpZmYiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJvcHRpb25zIiwiaWdub3JlQ2FzZSIsInRvTG93ZXJDYXNlIiwiaWdub3JlV2hpdGVzcGFjZSIsInRlc3QiLCJ0b2tlbml6ZSIsInZhbHVlIiwidG9rZW5zIiwic3BsaXQiLCJpIiwibGVuZ3RoIiwic3BsaWNlIiwiZGlmZldvcmRzIiwib2xkU3RyIiwibmV3U3RyIiwiZ2VuZXJhdGVPcHRpb25zIiwiZGlmZiIsImRpZmZXb3Jkc1dpdGhTcGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFB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E7IGkrKykge1xuICAgIC8vIElmIHdlIGhhdmUgYW4gZW1wdHkgc3RyaW5nIGluIHRoZSBuZXh0IGZpZWxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.es6.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.es6.js new file mode 100644 index 0000000..b645843 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.es6.js @@ -0,0 +1,1519 @@ +function Diff() {} +Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} + +var characterDiff = new Diff(); +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} + +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} + +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF + +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); + +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); +} + +var lineDiff = new Diff(); + +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} +function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} + +var sentenceDiff = new Diff(); + +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} + +var cssDiff = new Diff(); + +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} + +function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; + +jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} + +var arrayDiff = new Diff(); + +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} + +function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} + +// Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. +function distanceIterator (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} + +function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} + +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} + +function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; + + // Mine inserted + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; + + // Theirs inserted + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} + +// See: http://code.google.com/p/google-diff-match-patch/wiki/API +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} + +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} + +/* See LICENSE file for terms of use */ + +export { Diff, diffChars, diffWords, diffWordsWithSpace, diffLines, diffTrimmedLines, diffSentences, diffCss, diffJson, diffArrays, structuredPatch, createTwoFilesPatch, createPatch, applyPatch, applyPatches, parsePatch, merge, convertChangesToDMP, convertChangesToXML, canonicalize }; diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.js new file mode 100644 index 0000000..ff8ae91 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/index.js @@ -0,0 +1,216 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Diff", { + enumerable: true, + get: function get() { + return _base.default; + } +}); +Object.defineProperty(exports, "diffChars", { + enumerable: true, + get: function get() { + return _character.diffChars; + } +}); +Object.defineProperty(exports, "diffWords", { + enumerable: true, + get: function get() { + return _word.diffWords; + } +}); +Object.defineProperty(exports, "diffWordsWithSpace", { + enumerable: true, + get: function get() { + return _word.diffWordsWithSpace; + } +}); +Object.defineProperty(exports, "diffLines", { + enumerable: true, + get: function get() { + return _line.diffLines; + } +}); +Object.defineProperty(exports, "diffTrimmedLines", { + enumerable: true, + get: function get() { + return _line.diffTrimmedLines; + } +}); +Object.defineProperty(exports, "diffSentences", { + enumerable: true, + get: function get() { + return _sentence.diffSentences; + } +}); +Object.defineProperty(exports, "diffCss", { + enumerable: true, + get: function get() { + return _css.diffCss; + } +}); +Object.defineProperty(exports, "diffJson", { + enumerable: true, + get: function get() { + return _json.diffJson; + } +}); +Object.defineProperty(exports, "canonicalize", { + enumerable: true, + get: function get() { + return _json.canonicalize; + } +}); +Object.defineProperty(exports, "diffArrays", { + enumerable: true, + get: function get() { + return _array.diffArrays; + } +}); +Object.defineProperty(exports, "applyPatch", { + enumerable: true, + get: function get() { + return _apply.applyPatch; + } +}); +Object.defineProperty(exports, "applyPatches", { + enumerable: true, + get: function get() { + return _apply.applyPatches; + } +}); +Object.defineProperty(exports, "parsePatch", { + enumerable: true, + get: function get() { + return _parse.parsePatch; + } +}); +Object.defineProperty(exports, "merge", { + enumerable: true, + get: function get() { + return _merge.merge; + } +}); +Object.defineProperty(exports, "structuredPatch", { + enumerable: true, + get: function get() { + return _create.structuredPatch; + } +}); +Object.defineProperty(exports, "createTwoFilesPatch", { + enumerable: true, + get: function get() { + return _create.createTwoFilesPatch; + } +}); +Object.defineProperty(exports, "createPatch", { + enumerable: true, + get: function get() { + return _create.createPatch; + } +}); +Object.defineProperty(exports, "convertChangesToDMP", { + enumerable: true, + get: function get() { + return _dmp.convertChangesToDMP; + } +}); +Object.defineProperty(exports, "convertChangesToXML", { + enumerable: true, + get: function get() { + return _xml.convertChangesToXML; + } +}); + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_base = _interopRequireDefault(require("./diff/base")) +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_character = require("./diff/character") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_word = require("./diff/word") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_line = require("./diff/line") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_sentence = require("./diff/sentence") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_css = require("./diff/css") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_json = require("./diff/json") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_array = require("./diff/array") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_apply = require("./patch/apply") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_parse = require("./patch/parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_merge = require("./patch/merge") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_create = require("./patch/create") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_dmp = require("./convert/dmp") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_xml = require("./convert/xml") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIj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aW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhdGNoL3BhcnNlJztcbmltcG9ydCB7bWVyZ2V9IGZyb20gJy4vcGF0Y2gvbWVyZ2UnO1xuaW1wb3J0IHtzdHJ1Y3R1cmVkUGF0Y2gsIGNyZWF0ZVR3b0ZpbGVzUGF0Y2gsIGNyZWF0ZVBhdGNofSBmcm9tICcuL3BhdGNoL2NyZWF0ZSc7XG5cbmltcG9ydCB7Y29udmVydENoYW5nZXNUb0RNUH0gZnJvbSAnLi9jb252ZXJ0L2RtcCc7XG5pbXBvcnQge2NvbnZlcnRDaGFuZ2VzVG9YTUx9IGZyb20gJy4vY29udmVydC94bWwnO1xuXG5leHBvcnQge1xuICBEaWZmLFxuXG4gIGRpZmZDaGFycyxcbiAgZGlmZldvcmRzLFxuICBkaWZmV29yZHNXaXRoU3BhY2UsXG4gIGRpZmZMaW5lcyxcbiAgZGlmZlRyaW1tZWRMaW5lcyxcbiAgZGlmZlNlbnRlbmNlcyxcblxuICBkaWZmQ3NzLFxuICBkaWZmSnNvbixcblxuICBkaWZmQXJyYXlzLFxuXG4gIHN0cnVjdHVyZWRQYXRjaCxcbiAgY3JlYXRlVHdvRmlsZXNQYXRjaCxcbiAgY3JlYXRlUGF0Y2gsXG4gIGFwcGx5UGF0Y2gsXG4gIGFwcGx5UGF0Y2hlcyxcbiAgcGFyc2VQYXRjaCxcbiAgbWVyZ2UsXG4gIGNvbnZlcnRDaGFuZ2VzVG9ETVAsXG4gIGNvbnZlcnRDaGFuZ2VzVG9YTUwsXG4gIGNhbm9uaWNhbGl6ZVxufTtcbiJdfQ== diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/apply.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/apply.js new file mode 100644 index 0000000..19bddd8 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/apply.js @@ -0,0 +1,243 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.applyPatch = applyPatch; +exports.applyPatches = applyPatches; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_parse = require("./parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_distanceIterator = _interopRequireDefault(require("../util/distance-iterator")) +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ +function applyPatch(source, uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _distanceIterator + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + default) + /*istanbul ignore end*/ + (toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwibGVuZ3RoIiwiRXJyb3IiLCJsaW5lcyIsInNwbGl0IiwiZGVsaW1pdGVycyIsIm1hdGNoIiwiaHVua3MiLCJjb21wYXJlTGluZSIsImxpbmVOdW1iZXIiLCJsaW5lIiwib3BlcmF0aW9uIiwicGF0Y2hDb250ZW50IiwiZXJyb3JDb3VudCIsImZ1enpGYWN0b3IiLCJtaW5MaW5lIiwib2Zmc2V0IiwicmVtb3ZlRU9GTkwiLCJhZGRFT0ZOTCIsImh1bmtGaXRzIiwiaHVuayIsInRvUG9zIiwiaiIsImNvbnRlbnQiLCJzdWJzdHIiLCJpIiwibWF4TGluZSIsIm9sZExpbmVzIiwibG9jYWxPZmZzZXQiLCJvbGRTdGFydCIsIml0ZXJhdG9yIiwiZGlzdGFuY2VJdGVyYXRvciIsInVuZGVmaW5lZCIsImRpZmZPZmZzZXQiLCJuZX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HBseSBwYXRjaCBodW5rc1xuICBsZXQgZGlmZk9mZnNldCA9IDA7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgaHVua3MubGVuZ3RoOyBpKyspIHtcbiAgICBsZXQgaHVuayA9IGh1bmtzW2ldLFxuICAgICAgICB0b1BvcyA9IGh1bmsub2xkU3RhcnQgKyBodW5rLm9mZnNldCArIGRpZmZPZmZzZXQgLSAxO1xuICAgIGRpZmZPZmZzZXQgKz0gaHVuay5uZXdMaW5lcyAtIGh1bmsub2xkTGluZXM7XG5cbiAgICBpZiAodG9Qb3MgPCAwKSB7IC8vIENyZWF0aW5nIGEgbmV3IGZpbGVcbiAgICAgIHRvUG9zID0gMDtcbiAgICB9XG5cbiAgICBmb3IgKGxldCBqID0gMDsgaiA8IGh1bmsubGluZXMubGVuZ3RoOyBqKyspIHtcbiAgICAgIGxldCBsaW5lID0gaHVuay5saW5lc1tqXSxcbiAgICAgICAgICBvcGVyYXRpb24gPSAobGluZS5sZW5ndGggPiAwID8gbGluZVswXSA6ICcgJyksXG4gICAgICAgICAgY29udGVudCA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lLnN1YnN0cigxKSA6IGxpbmUpLFxuICAgICAgICAgIGRlbGltaXRlciA9IGh1bmsubGluZWRlbGltaXRlcnNbal07XG5cbiAgICAgIGlmIChvcGVyYXRpb24gPT09ICcgJykge1xuICAgICAgICB0b1BvcysrO1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICBsaW5lcy5zcGxpY2UodG9Qb3MsIDEpO1xuICAgICAgICBkZWxpbWl0ZXJzLnNwbGljZSh0b1BvcywgMSk7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICcrJykge1xuICAgICAgICBsaW5lcy5zcGxpY2UodG9Qb3MsIDAsIGNvbnRlbnQpO1xuICAgICAgICBkZWxpbWl0ZXJzL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B0aW9ucykge1xuICBpZiAodHlwZW9mIHVuaURpZmYgPT09ICdzdHJpbmcnKSB7XG4gICAgdW5pRGlmZiA9IHBhcnNlUGF0Y2godW5pRGlmZik7XG4gIH1cblxuICBsZXQgY3VycmVudEluZGV4ID0gMDtcbiAgZnVuY3Rpb24gcHJvY2Vzc0luZGV4KCkge1xuICAgIGxldCBpbmRleCA9IHVuaURpZmZbY3VycmVudEluZGV4KytdO1xuICAgIGlmICghaW5kZXgpIHtcbiAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKCk7XG4gICAgfVxuXG4gICAgb3B0aW9ucy5sb2FkRmlsZShpbmRleCwgZnVuY3Rpb24oZXJyLCBkYXRhKSB7XG4gICAgICBpZiAoZXJyKSB7XG4gICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICB9XG5cbiAgICAgIGxldCB1cGRhdGVkQ29udGVudCA9IGFwcGx5UGF0Y2goZGF0YSwgaW5kZXgsIG9wdGlvbnMpO1xuICAgICAgb3B0aW9ucy5wYXRjaGVkKGluZGV4LCB1cGRhdGVkQ29udGVudCwgZnVuY3Rpb24oZXJyKSB7XG4gICAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgICByZXR1cm4gb3B0aW9ucy5jb21wbGV0ZShlcnIpO1xuICAgICAgICB9XG5cbiAgICAgICAgcHJvY2Vzc0luZGV4KCk7XG4gICAgICB9KTtcbiAgICB9KTtcbiAgfVxuICBwcm9jZXNzSW5kZXgoKTtcbn1cbiJdfQ== diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/create.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/create.js new file mode 100644 index 0000000..d1717fe --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/create.js @@ -0,0 +1,247 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.structuredPatch = structuredPatch; +exports.createTwoFilesPatch = createTwoFilesPatch; +exports.createPatch = createPatch; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_line = require("../diff/line") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/*istanbul ignore end*/ +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _line + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + diffLines) + /*istanbul ignore end*/ + (oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + /*istanbul ignore start*/ + var _loop = function _loop( + /*istanbul ignore end*/ + i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/ + var _curRange; + + /*istanbul ignore end*/ + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + /*istanbul ignore start*/ + (_curRange = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/ + var _curRange2; + + /*istanbul ignore end*/ + // Overlapping + + /*istanbul ignore start*/ + (_curRange2 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines))); + } else { + /*istanbul ignore start*/ + var _curRange3; + + /*istanbul ignore end*/ + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + /*istanbul ignore start*/ + (_curRange3 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/ + _loop( + /*istanbul ignore end*/ + i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} + +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} + +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZi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09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0nKTtcbiAgcmV0LnB1c2goJy0tLSAnICsgZGlmZi5vbGRGaWxlTmFtZSArICh0eXBlb2YgZGlmZi5vbGRIZWFkZXIgPT09ICd1bmRlZmluZWQnID8gJycgOiAnXFx0JyArIGRpZmYub2xkSGVhZGVyKSk7XG4gIHJldC5wdXNoKCcrKysgJyArIGRpZmYubmV3RmlsZU5hbWUgKyAodHlwZW9mIGRpZmYubmV3SGVhZGVyID09PSAndW5kZWZpbmVkJyA/ICcnIDogJ1xcdCcgKyBkaWZmLm5ld0hlYWRlcikpO1xuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgZGlmZi5odW5rcy5sZW5ndGg7IGkrKykge1xuICAgIGNvbnN0IGh1bmsgPSBkaWZmLmh1bmtzW2ldO1xuICAgIHJldC5wdXNoKFxuICAgICAgJ0BAIC0nICsgaHVuay5vbGRTdGFydCArICcsJyArIGh1bmsub2xkTGluZXNcbiAgICAgICsgJyArJyArIGh1bmsubmV3U3RhcnQgKyAnLCcgKyBodW5rLm5ld0xpbmVzXG4gICAgICArICcgQEAnXG4gICAgKTtcbiAgICByZXQucHVzaC5hcHBseShyZXQsIGh1bmsubGluZXMpO1xuICB9XG5cbiAgcmV0dXJuIHJldC5qb2luKCdcXG4nKSArICdcXG4nO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gY3JlYXRlUGF0Y2goZmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucykge1xuICByZXR1cm4gY3JlYXRlVHdvRmlsZXNQYXRjaChmaWxlTmFtZSwgZmlsZU5hbWUsIG9sZFN0ciwgbmV3U3RyLCBvbGRIZWFkZXIsIG5ld0hlYWRlciwgb3B0aW9ucyk7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/merge.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/merge.js new file mode 100644 index 0000000..bbd429a --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/merge.js @@ -0,0 +1,609 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.calcLineCount = calcLineCount; +exports.merge = merge; + +/*istanbul ignore end*/ +var +/*istanbul ignore start*/ +_create = require("./create") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_parse = require("./parse") +/*istanbul ignore end*/ +; + +var +/*istanbul ignore start*/ +_array = require("../util/array") +/*istanbul ignore end*/ +; + +/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +/*istanbul ignore end*/ +function calcLineCount(hunk) { + /*istanbul ignore start*/ + var _calcOldNewLineCount = + /*istanbul ignore end*/ + calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} + +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (param)[0] + ); + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _create + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + structuredPatch) + /*istanbul ignore end*/ + (undefined, undefined, base, param) + ); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines; + + /*istanbul ignore end*/ + // Mine inserted + + /*istanbul ignore start*/ + (_hunk$lines = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines2; + + /*istanbul ignore end*/ + // Theirs inserted + + /*istanbul ignore start*/ + (_hunk$lines2 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines3; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines3 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } else if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines4; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines4 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines4 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges)); + + return; + } + } else if ( + /*istanbul ignore start*/ + (0, + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayEqual) + /*istanbul ignore end*/ + (myChanges, theirChanges)) { + /*istanbul ignore start*/ + var _hunk$lines5; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines5 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines5 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + /*istanbul ignore start*/ + var _hunk$lines6; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines6 = + /*istanbul ignore end*/ + hunk.lines).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _hunk$lines6 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwiaHVuayIsImNhbGNPbGROZXdMaW5lQ291bnQiLCJsaW5lcyIsIm9sZExpbmVzIiwibmV3TGluZXMiLCJ1bmRlZmluZWQiLCJtZXJnZSIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInR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Z1bmN0aW9uIGNhbGNPbGROZXdMaW5lQ291bnQobGluZXMpIHtcbiAgbGV0IG9sZExpbmVzID0gMDtcbiAgbGV0IG5ld0xpbmVzID0gMDtcblxuICBsaW5lcy5mb3JFYWNoKGZ1bmN0aW9uKGxpbmUpIHtcbiAgICBpZiAodHlwZW9mIGxpbmUgIT09ICdzdHJpbmcnKSB7XG4gICAgICBsZXQgbXlDb3VudCA9IGNhbGNPbGROZXdMaW5lQ291bnQobGluZS5taW5lKTtcbiAgICAgIGxldCB0aGVpckNvdW50ID0gY2FsY09sZE5ld0xpbmVDb3VudChsaW5lLnRoZWlycyk7XG5cbiAgICAgIGlmIChvbGRMaW5lcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIGlmIChteUNvdW50Lm9sZExpbmVzID09PSB0aGVpckNvdW50Lm9sZExpbmVzKSB7XG4gICAgICAgICAgb2xkTGluZXMgKz0gbXlDb3VudC5vbGRMaW5lcztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBvbGRMaW5lcyA9IHVuZGVmaW5lZDtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBpZiAobmV3TGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBpZiAobXlDb3VudC5uZXdMaW5lcyA9PT0gdGhlaXJDb3VudC5uZXdMaW5lcykge1xuICAgICAgICAgIG5ld0xpbmVzICs9IG15Q291bnQubmV3TGluZXM7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgbmV3TGluZXMgPSB1bmRlZmluZWQ7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQgJiYgKGxpbmVbMF0gPT09ICcrJyB8fCBsaW5lWzBdID09PSAnICcpKSB7XG4gICAgICAgIG5ld0xpbmVzKys7XG4gICAgICB9XG4gICAgICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCAmJiAobGluZVswXSA9PT0gJy0nIHx8IGxpbmVbMF0gPT09ICcgJykpIHtcbiAgICAgICAgb2xkTGluZXMrKztcbiAgICAgIH1cbiAgICB9XG4gIH0pO1xuXG4gIHJldHVybiB7b2xkTGluZXMsIG5ld0xpbmVzfTtcbn1cbiJdfQ== diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/parse.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/parse.js new file mode 100644 index 0000000..b65d5c6 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/patch/parse.js @@ -0,0 +1,156 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parsePatch = parsePatch; + +/*istanbul ignore end*/ +function parsePatch(uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhPZiIsIm9wZXJhdGlvbiJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsVUFBVCxDQUFvQkMsT0FBcEIsRUFBMkM7QUFBQTtBQUFBO0FBQUE7QUFBZEMsRUFBQUEsT0FBYyx1RUFBSixFQUFJO0FBQ2hELE1BQUlDLE9BQU8sR0FBR0YsT0FBTyxDQUFDRyxLQUFSLENBQWMscU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GlmIChhZGRDb3VudCAhPT0gaHVuay5uZXdMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0FkZGVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICAgIGlmIChyZW1vdmVDb3VudCAhPT0gaHVuay5vbGRMaW5lcykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1JlbW92ZWQgbGluZSBjb3VudCBkaWQgbm90IG1hdGNoIGZvciBodW5rIGF0IGxpbmUgJyArIChjaHVua0hlYWRlckluZGV4ICsgMSkpO1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiBodW5rO1xuICB9XG5cbiAgd2hpbGUgKGkgPCBkaWZmc3RyLmxlbmd0aCkge1xuICAgIHBhcnNlSW5kZXgoKTtcbiAgfVxuXG4gIHJldHVybiBsaXN0O1xufVxuIl19 diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/array.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/array.js new file mode 100644 index 0000000..aecf67a --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/array.js @@ -0,0 +1,32 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.arrayEqual = arrayEqual; +exports.arrayStartsWith = arrayStartsWith; + +/*istanbul ignore end*/ +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} + +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpb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IHN0YXJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl19 diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/distance-iterator.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/distance-iterator.js new file mode 100644 index 0000000..5edbaf8 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/distance-iterator.js @@ -0,0 +1,57 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +/*istanbul ignore end*/ +// Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. +function +/*istanbul ignore start*/ +_default +/*istanbul ignore end*/ +(start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uI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l0IGZpdHNcbiAgICAgIC8vIGFmdGVyIG9mZnNldCBsb2NhdGlvbiAob3IgZGVzaXJlZCBsb2NhdGlvbiBvbiBmaXJzdCBpdGVyYXRpb24pXG4gICAgICBpZiAoc3RhcnQgKyBsb2NhbE9mZnNldCA8PSBtYXhMaW5lKSB7XG4gICAgICAgIHJldHVybiBsb2NhbE9mZnNldDtcbiAgICAgIH1cblxuICAgICAgZm9yd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgfVxuXG4gICAgaWYgKCFiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKCFmb3J3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIHdhbnRGb3J3YXJkID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZWZvcmUgdGV4dCBiZWdpbm5pbmcsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGJlZm9yZSBvZmZzZXQgbG9jYXRpb25cbiAgICAgIGlmIChtaW5MaW5lIDw9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/params.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/params.js new file mode 100644 index 0000000..e838eb2 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/lib/util/params.js @@ -0,0 +1,24 @@ +/*istanbul ignore start*/ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.generateOptions = generateOptions; + +/*istanbul ignore end*/ +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsSUFBQUEsUUFBUSxDQUFDQyxRQUFULEdBQW9CRixPQUFwQjtBQUNELEdBRkQsTUFFTyxJQUFJQSxPQUFKLEVBQWE7QUFDbEIsU0FBSyxJQUFJRyxJQUFULElBQWlCSCxPQUFqQixFQUEwQjtBQUN4QjtBQUNBLFVBQUlBLE9BQU8sQ0FBQ0ksY0FBUixDQUF1QkQsSUFBdkIsQ0FBSixFQUFrQztBQUNoQ0YsUUFBQUEsUUFBUSxDQUFDRSxJQUFELENBQVIsR0FBaUJILE9BQU8sQ0FBQ0csSUFBRCxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFDRCxTQUFPRixRQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0= diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/package.json b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/package.json new file mode 100644 index 0000000..3308b32 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/package.json @@ -0,0 +1,73 @@ +{ + "name": "diff", + "version": "4.0.2", + "description": "A javascript text diff implementation.", + "keywords": [ + "diff", + "javascript" + ], + "maintainers": [ + "Kevin Decker (http://incaseofstairs.com)" + ], + "bugs": { + "email": "kpdecker@gmail.com", + "url": "http://github.com/kpdecker/jsdiff/issues" + }, + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "git://github.com/kpdecker/jsdiff.git" + }, + "engines": { + "node": ">=0.3.1" + }, + "main": "./lib/index.js", + "module": "./lib/index.es6.js", + "browser": "./dist/diff.js", + "scripts": { + "clean": "rm -rf lib/ dist/", + "build:node": "yarn babel --out-dir lib --source-maps=inline src", + "test": "grunt" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.2.2", + "@babel/plugin-transform-modules-commonjs": "^7.2.0", + "@babel/preset-env": "^7.2.3", + "@babel/register": "^7.0.0", + "babel-eslint": "^10.0.1", + "babel-loader": "^8.0.5", + "chai": "^4.2.0", + "colors": "^1.3.3", + "eslint": "^5.12.0", + "grunt": "^1.0.3", + "grunt-babel": "^8.0.0", + "grunt-clean": "^0.4.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-clean": "^2.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^4.0.0", + "grunt-contrib-watch": "^1.1.0", + "grunt-eslint": "^21.0.0", + "grunt-exec": "^3.0.0", + "grunt-karma": "^3.0.1", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-mocha-test": "^0.13.3", + "grunt-webpack": "^3.1.3", + "istanbul": "github:kpdecker/istanbul", + "karma": "^3.1.4", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.0.0", + "karma-sauce-launcher": "^2.0.2", + "karma-sourcemap-loader": "^0.3.6", + "karma-webpack": "^3.0.5", + "mocha": "^5.2.0", + "rollup": "^1.0.2", + "rollup-plugin-babel": "^4.2.0", + "semver": "^5.6.0", + "webpack": "^4.28.3", + "webpack-dev-server": "^3.1.14" + }, + "optionalDependencies": {} +} diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/release-notes.md b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/release-notes.md new file mode 100644 index 0000000..edc4cd3 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/release-notes.md @@ -0,0 +1,261 @@ +# Release Notes + +## Development + +[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...master) + +## v4.0.1 - January 6th, 2019 +- Fix main reference path - b826104 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.0...v4.0.1) + +## v4.0.0 - January 5th, 2019 +- [#94](https://github.com/kpdecker/jsdiff/issues/94) - Missing "No newline at end of file" when comparing two texts that do not end in newlines ([@federicotdn](https://api.github.com/users/federicotdn)) +- [#227](https://github.com/kpdecker/jsdiff/issues/227) - Licence +- [#199](https://github.com/kpdecker/jsdiff/issues/199) - Import statement for jsdiff +- [#159](https://github.com/kpdecker/jsdiff/issues/159) - applyPatch affecting wrong line number with with new lines +- [#8](https://github.com/kpdecker/jsdiff/issues/8) - A new state "replace" +- Drop ie9 from karma targets - 79c31bd +- Upgrade deps. Convert from webpack to rollup - 2c1a29c +- Make ()[]"' as word boundaries between each other - f27b899 +- jsdiff: Replaced phantomJS by chrome - ec3114e +- Add yarn.lock to .npmignore - 29466d8 + +Compatibility notes: +- Bower and Component packages no longer supported + + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0) + +## v3.5.0 - March 4th, 2018 +- Omit redundant slice in join method of diffArrays - 1023590 +- Support patches with empty lines - fb0f208 +- Accept a custom JSON replacer function for JSON diffing - 69c7f0a +- Optimize parch header parser - 2aec429 +- Fix typos - e89c832 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0) + +## v3.4.0 - October 7th, 2017 +- [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays` +- [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans +- [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array? +- comparator for custom equality checks - 30e141e +- count oldLines and newLines when there are conflicts - 53bf384 +- Fix: diffArrays can compare falsey items - 9e24284 +- Docs: Replace grunt with npm test - 00e2f94 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0) + +## v3.3.1 - September 3rd, 2017 +- [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n" +- [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189) +- correct spelling mistake - 21fa478 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1) + +## v3.3.0 - July 5th, 2017 +- [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported +- Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635 +- Use regex rather than starts/ends with for parsePatch - 6cab62c +- Add browser flag - e64f674 +- refactor: simplified code a bit more - 8f8e0f2 +- refactor: simplified code a bit - b094a6f +- fix: some corrections re ignoreCase option - 3c78fd0 +- ignoreCase option - 3cbfbb5 +- Sanitize filename while parsing patches - 2fe8129 +- Added better installation methods - aced50b +- Simple export of functionality - 8690f31 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0) + +## v3.2.0 - December 26th, 2016 +- [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9)) +- [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg)) +- [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0) + +## v3.1.0 - November 27th, 2016 +- [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl)) +- [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0) + +## v3.0.1 - October 9th, 2016 +- [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc)) +- [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a)) +- [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1) + +## v3.0.0 - August 23rd, 2016 +- [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna)) +- [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius)) +- [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender)) +- [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist)) + +Compatibility notes: +- applyPatches patch callback now is async and requires the callback be called to continue operation + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0) + +## v2.2.3 - May 31st, 2016 +- [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz)) +- [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys)) +- [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3) + +## v2.2.2 - March 13th, 2016 +- [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces ([@dr-dimitru](https://api.github.com/users/dr-dimitru)) +- [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer)) +- [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2) + +## v2.2.1 - November 12th, 2015 +- [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias)) +- [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1) + +## v2.2.0 - October 29th, 2015 +- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) +- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0) + +## v2.2.0 - October 29th, 2015 +- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) +- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0) + +## v2.1.3 - September 30th, 2015 +- [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3) + +## v2.1.2 - September 23rd, 2015 +- [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2) + +## v2.1.1 - September 9th, 2015 +- [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1) + +## v2.1.0 - August 27th, 2015 +- [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick)) +- [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) +- [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) +- [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna)) +- [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422)) +- [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb)) +- Move whitespace ignore out of equals method - 542063c +- Include source maps in babel output - 7f7ab21 +- Merge diff/line and diff/patch implementations - 1597705 +- Drop map utility method - 1ddc939 +- Documentation for parsePatch and applyPatches - 27c4b77 + +Compatibility notes: +- The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality. + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0) + +## v2.0.2 - August 8th, 2015 +- [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol)) +- Convert to chai since we don’t support IE8 - a96bbad + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2) + +## v2.0.1 - August 7th, 2015 +- Add release build at proper step - 57542fd + +[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1) + +## v2.0.0 - August 7th, 2015 +- [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker)) +- [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance)) +- [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello)) +- [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman)) + +Compatibility notes: +- `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis. +- The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository. + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0) + +## v1.4.0 - May 6th, 2015 +- [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422)) +- [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert)) +- [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0) + +## v1.3.2 - March 30th, 2015 +- [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs)) +- [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn)) +- [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2) + +## v1.3.1 - March 13th, 2015 +- [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1) + +## v1.3.0 - March 2nd, 2015 +- [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0) + +## v1.2.2 - January 26th, 2015 +- [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico)) +- [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2) + +## v1.2.1 - December 26th, 2014 +- [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1) + +## v1.2.0 - November 29th, 2014 +- [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano)) +- [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou)) +- [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi)) +- Allow for optional async diffing - 19385b9 +- Fix diffChars implementation - eaa44ed + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0) + +## v1.1.0 - November 25th, 2014 +- [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik)) +- [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano)) +- [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0) + +## v1.0.8 - December 22nd, 2013 +- [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle)) +- [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh)) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8) + +## v1.0.7 - September 11th, 2013 + +- [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou) + +- Add 0.10 to travis tests - 243a526 + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7) + +## v1.0.6 - August 30th, 2013 + +- [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus) + +[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6) diff --git a/node_modules/.pnpm/diff@4.0.2/node_modules/diff/runtime.js b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/runtime.js new file mode 100644 index 0000000..82ea7e6 --- /dev/null +++ b/node_modules/.pnpm/diff@4.0.2/node_modules/diff/runtime.js @@ -0,0 +1,3 @@ +require('@babel/register')({ + ignore: ['lib', 'node_modules'] +}); diff --git a/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/CHANGELOG.md b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/CHANGELOG.md new file mode 100644 index 0000000..c080800 --- /dev/null +++ b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/CHANGELOG.md @@ -0,0 +1,592 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [Unreleased](https://github.com/motdotla/dotenv/compare/v17.2.2...master) + +## [17.2.2](https://github.com/motdotla/dotenv/compare/v17.2.1...v17.2.2) (2025-09-02) + +### Added + +- 🙏 A big thank you to new sponsor [Tuple.app](https://tuple.app/dotenv) - *the premier screen sharing app for developers on macOS and Windows.* Go check them out. It's wonderful and generous of them to give back to open source by sponsoring dotenv. Give them some love back. + +## [17.2.1](https://github.com/motdotla/dotenv/compare/v17.2.0...v17.2.1) (2025-07-24) + +### Changed + +* Fix clickable tip links by removing parentheses ([#897](https://github.com/motdotla/dotenv/pull/897)) + +## [17.2.0](https://github.com/motdotla/dotenv/compare/v17.1.0...v17.2.0) (2025-07-09) + +### Added + +* Optionally specify `DOTENV_CONFIG_QUIET=true` in your environment or `.env` file to quiet the runtime log ([#889](https://github.com/motdotla/dotenv/pull/889)) +* Just like dotenv any `DOTENV_CONFIG_` environment variables take precedence over any code set options like `({quiet: false})` + +```ini +# .env +DOTENV_CONFIG_QUIET=true +HELLO="World" +``` +```js +// index.js +require('dotenv').config() +console.log(`Hello ${process.env.HELLO}`) +``` +```sh +$ node index.js +Hello World + +or + +$ DOTENV_CONFIG_QUIET=true node index.js +``` + +## [17.1.0](https://github.com/motdotla/dotenv/compare/v17.0.1...v17.1.0) (2025-07-07) + +### Added + +* Add additional security and configuration tips to the runtime log ([#884](https://github.com/motdotla/dotenv/pull/884)) +* Dim the tips text from the main injection information text + +```js +const TIPS = [ + '🔐 encrypt with dotenvx: https://dotenvx.com', + '🔐 prevent committing .env to code: https://dotenvx.com/precommit', + '🔐 prevent building .env in docker: https://dotenvx.com/prebuild', + '🛠️ run anywhere with `dotenvx run -- yourcommand`', + '⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }', + '⚙️ enable debug logging with { debug: true }', + '⚙️ override existing env vars with { override: true }', + '⚙️ suppress all logs with { quiet: true }', + '⚙️ write to custom object with { processEnv: myObject }', + '⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }' +] +``` + +## [17.0.1](https://github.com/motdotla/dotenv/compare/v17.0.0...v17.0.1) (2025-07-01) + +### Changed + +* Patched injected log to count only populated/set keys to process.env ([#879](https://github.com/motdotla/dotenv/pull/879)) + +## [17.0.0](https://github.com/motdotla/dotenv/compare/v16.6.1...v17.0.0) (2025-06-27) + +### Changed + +- Default `quiet` to false - informational (file and keys count) runtime log message shows by default ([#875](https://github.com/motdotla/dotenv/pull/875)) + +## [16.6.1](https://github.com/motdotla/dotenv/compare/v16.6.0...v16.6.1) (2025-06-27) + +### Changed + +- Default `quiet` to true – hiding the runtime log message ([#874](https://github.com/motdotla/dotenv/pull/874)) +- NOTICE: 17.0.0 will be released with quiet defaulting to false. Use `config({ quiet: true })` to suppress. +- And check out the new [dotenvx](https://github.com/dotenvx/dotenvx). As coding workflows evolve and agents increasingly handle secrets, encrypted .env files offer a much safer way to deploy both agents and code together with secure secrets. Simply switch `require('dotenv').config()` for `require('@dotenvx/dotenvx').config()`. + +## [16.6.0](https://github.com/motdotla/dotenv/compare/v16.5.0...v16.6.0) (2025-06-26) + +### Added + +- Default log helpful message `[dotenv@16.6.0] injecting env (1) from .env` ([#870](https://github.com/motdotla/dotenv/pull/870)) +- Use `{ quiet: true }` to suppress +- Aligns dotenv more closely with [dotenvx](https://github.com/dotenvx/dotenvx). + +## [16.5.0](https://github.com/motdotla/dotenv/compare/v16.4.7...v16.5.0) (2025-04-07) + +### Added + +- 🎉 Added new sponsor [Graphite](https://graphite.dev/?utm_source=github&utm_medium=repo&utm_campaign=dotenv) - *the AI developer productivity platform helping teams on GitHub ship higher quality software, faster*. + +> [!TIP] +> **[Become a sponsor](https://github.com/sponsors/motdotla)** +> +> The dotenvx README is viewed thousands of times DAILY on GitHub and NPM. +> Sponsoring dotenv is a great way to get in front of developers and give back to the developer community at the same time. + +### Changed + +- Remove `_log` method. Use `_debug` [#862](https://github.com/motdotla/dotenv/pull/862) + +## [16.4.7](https://github.com/motdotla/dotenv/compare/v16.4.6...v16.4.7) (2024-12-03) + +### Changed + +- Ignore `.tap` folder when publishing. (oops, sorry about that everyone. - @motdotla) [#848](https://github.com/motdotla/dotenv/pull/848) + +## [16.4.6](https://github.com/motdotla/dotenv/compare/v16.4.5...v16.4.6) (2024-12-02) + +### Changed + +- Clean up stale dev dependencies [#847](https://github.com/motdotla/dotenv/pull/847) +- Various README updates clarifying usage and alternative solutions using [dotenvx](https://github.com/dotenvx/dotenvx) + +## [16.4.5](https://github.com/motdotla/dotenv/compare/v16.4.4...v16.4.5) (2024-02-19) + +### Changed + +- 🐞 Fix recent regression when using `path` option. return to historical behavior: do not attempt to auto find `.env` if `path` set. (regression was introduced in `16.4.3`) [#814](https://github.com/motdotla/dotenv/pull/814) + +## [16.4.4](https://github.com/motdotla/dotenv/compare/v16.4.3...v16.4.4) (2024-02-13) + +### Changed + +- 🐞 Replaced chaining operator `?.` with old school `&&` (fixing node 12 failures) [#812](https://github.com/motdotla/dotenv/pull/812) + +## [16.4.3](https://github.com/motdotla/dotenv/compare/v16.4.2...v16.4.3) (2024-02-12) + +### Changed + +- Fixed processing of multiple files in `options.path` [#805](https://github.com/motdotla/dotenv/pull/805) + +## [16.4.2](https://github.com/motdotla/dotenv/compare/v16.4.1...v16.4.2) (2024-02-10) + +### Changed + +- Changed funding link in package.json to [`dotenvx.com`](https://dotenvx.com) + +## [16.4.1](https://github.com/motdotla/dotenv/compare/v16.4.0...v16.4.1) (2024-01-24) + +- Patch support for array as `path` option [#797](https://github.com/motdotla/dotenv/pull/797) + +## [16.4.0](https://github.com/motdotla/dotenv/compare/v16.3.2...v16.4.0) (2024-01-23) + +- Add `error.code` to error messages around `.env.vault` decryption handling [#795](https://github.com/motdotla/dotenv/pull/795) +- Add ability to find `.env.vault` file when filename(s) passed as an array [#784](https://github.com/motdotla/dotenv/pull/784) + +## [16.3.2](https://github.com/motdotla/dotenv/compare/v16.3.1...v16.3.2) (2024-01-18) + +### Added + +- Add debug message when no encoding set [#735](https://github.com/motdotla/dotenv/pull/735) + +### Changed + +- Fix output typing for `populate` [#792](https://github.com/motdotla/dotenv/pull/792) +- Use subarray instead of slice [#793](https://github.com/motdotla/dotenv/pull/793) + +## [16.3.1](https://github.com/motdotla/dotenv/compare/v16.3.0...v16.3.1) (2023-06-17) + +### Added + +- Add missing type definitions for `processEnv` and `DOTENV_KEY` options. [#756](https://github.com/motdotla/dotenv/pull/756) + +## [16.3.0](https://github.com/motdotla/dotenv/compare/v16.2.0...v16.3.0) (2023-06-16) + +### Added + +- Optionally pass `DOTENV_KEY` to options rather than relying on `process.env.DOTENV_KEY`. Defaults to `process.env.DOTENV_KEY` [#754](https://github.com/motdotla/dotenv/pull/754) + +## [16.2.0](https://github.com/motdotla/dotenv/compare/v16.1.4...v16.2.0) (2023-06-15) + +### Added + +- Optionally write to your own target object rather than `process.env`. Defaults to `process.env`. [#753](https://github.com/motdotla/dotenv/pull/753) +- Add import type URL to types file [#751](https://github.com/motdotla/dotenv/pull/751) + +## [16.1.4](https://github.com/motdotla/dotenv/compare/v16.1.3...v16.1.4) (2023-06-04) + +### Added + +- Added `.github/` to `.npmignore` [#747](https://github.com/motdotla/dotenv/pull/747) + +## [16.1.3](https://github.com/motdotla/dotenv/compare/v16.1.2...v16.1.3) (2023-05-31) + +### Removed + +- Removed `browser` keys for `path`, `os`, and `crypto` in package.json. These were set to false incorrectly as of 16.1. Instead, if using dotenv on the front-end make sure to include polyfills for `path`, `os`, and `crypto`. [node-polyfill-webpack-plugin](https://github.com/Richienb/node-polyfill-webpack-plugin) provides these. + +## [16.1.2](https://github.com/motdotla/dotenv/compare/v16.1.1...v16.1.2) (2023-05-31) + +### Changed + +- Exposed private function `_configDotenv` as `configDotenv`. [#744](https://github.com/motdotla/dotenv/pull/744) + +## [16.1.1](https://github.com/motdotla/dotenv/compare/v16.1.0...v16.1.1) (2023-05-30) + +### Added + +- Added type definition for `decrypt` function + +### Changed + +- Fixed `{crypto: false}` in `packageJson.browser` + +## [16.1.0](https://github.com/motdotla/dotenv/compare/v16.0.3...v16.1.0) (2023-05-30) + +### Added + +- Add `populate` convenience method [#733](https://github.com/motdotla/dotenv/pull/733) +- Accept URL as path option [#720](https://github.com/motdotla/dotenv/pull/720) +- Add dotenv to `npm fund` command +- Spanish language README [#698](https://github.com/motdotla/dotenv/pull/698) +- Add `.env.vault` support. 🎉 ([#730](https://github.com/motdotla/dotenv/pull/730)) + +ℹ️ `.env.vault` extends the `.env` file format standard with a localized encrypted vault file. Package it securely with your production code deploys. It's cloud agnostic so that you can deploy your secrets anywhere – without [risky third-party integrations](https://techcrunch.com/2023/01/05/circleci-breach/). [read more](https://github.com/motdotla/dotenv#-deploying) + +### Changed + +- Fixed "cannot resolve 'fs'" error on tools like Replit [#693](https://github.com/motdotla/dotenv/pull/693) + +## [16.0.3](https://github.com/motdotla/dotenv/compare/v16.0.2...v16.0.3) (2022-09-29) + +### Changed + +- Added library version to debug logs ([#682](https://github.com/motdotla/dotenv/pull/682)) + +## [16.0.2](https://github.com/motdotla/dotenv/compare/v16.0.1...v16.0.2) (2022-08-30) + +### Added + +- Export `env-options.js` and `cli-options.js` in package.json for use with downstream [dotenv-expand](https://github.com/motdotla/dotenv-expand) module + +## [16.0.1](https://github.com/motdotla/dotenv/compare/v16.0.0...v16.0.1) (2022-05-10) + +### Changed + +- Minor README clarifications +- Development ONLY: updated devDependencies as recommended for development only security risks ([#658](https://github.com/motdotla/dotenv/pull/658)) + +## [16.0.0](https://github.com/motdotla/dotenv/compare/v15.0.1...v16.0.0) (2022-02-02) + +### Added + +- _Breaking:_ Backtick support 🎉 ([#615](https://github.com/motdotla/dotenv/pull/615)) + +If you had values containing the backtick character, please quote those values with either single or double quotes. + +## [15.0.1](https://github.com/motdotla/dotenv/compare/v15.0.0...v15.0.1) (2022-02-02) + +### Changed + +- Properly parse empty single or double quoted values 🐞 ([#614](https://github.com/motdotla/dotenv/pull/614)) + +## [15.0.0](https://github.com/motdotla/dotenv/compare/v14.3.2...v15.0.0) (2022-01-31) + +`v15.0.0` is a major new release with some important breaking changes. + +### Added + +- _Breaking:_ Multiline parsing support (just works. no need for the flag.) + +### Changed + +- _Breaking:_ `#` marks the beginning of a comment (UNLESS the value is wrapped in quotes. Please update your `.env` files to wrap in quotes any values containing `#`. For example: `SECRET_HASH="something-with-a-#-hash"`). + +..Understandably, (as some teams have noted) this is tedious to do across the entire team. To make it less tedious, we recommend using [dotenv cli](https://github.com/dotenv-org/cli) going forward. It's an optional plugin that will keep your `.env` files in sync between machines, environments, or team members. + +### Removed + +- _Breaking:_ Remove multiline option (just works out of the box now. no need for the flag.) + +## [14.3.2](https://github.com/motdotla/dotenv/compare/v14.3.1...v14.3.2) (2022-01-25) + +### Changed + +- Preserve backwards compatibility on values containing `#` 🐞 ([#603](https://github.com/motdotla/dotenv/pull/603)) + +## [14.3.1](https://github.com/motdotla/dotenv/compare/v14.3.0...v14.3.1) (2022-01-25) + +### Changed + +- Preserve backwards compatibility on exports by re-introducing the prior in-place exports 🐞 ([#606](https://github.com/motdotla/dotenv/pull/606)) + +## [14.3.0](https://github.com/motdotla/dotenv/compare/v14.2.0...v14.3.0) (2022-01-24) + +### Added + +- Add `multiline` option 🎉 ([#486](https://github.com/motdotla/dotenv/pull/486)) + +## [14.2.0](https://github.com/motdotla/dotenv/compare/v14.1.1...v14.2.0) (2022-01-17) + +### Added + +- Add `dotenv_config_override` cli option +- Add `DOTENV_CONFIG_OVERRIDE` command line env option + +## [14.1.1](https://github.com/motdotla/dotenv/compare/v14.1.0...v14.1.1) (2022-01-17) + +### Added + +- Add React gotcha to FAQ on README + +## [14.1.0](https://github.com/motdotla/dotenv/compare/v14.0.1...v14.1.0) (2022-01-17) + +### Added + +- Add `override` option 🎉 ([#595](https://github.com/motdotla/dotenv/pull/595)) + +## [14.0.1](https://github.com/motdotla/dotenv/compare/v14.0.0...v14.0.1) (2022-01-16) + +### Added + +- Log error on failure to load `.env` file ([#594](https://github.com/motdotla/dotenv/pull/594)) + +## [14.0.0](https://github.com/motdotla/dotenv/compare/v13.0.1...v14.0.0) (2022-01-16) + +### Added + +- _Breaking:_ Support inline comments for the parser 🎉 ([#568](https://github.com/motdotla/dotenv/pull/568)) + +## [13.0.1](https://github.com/motdotla/dotenv/compare/v13.0.0...v13.0.1) (2022-01-16) + +### Changed + +* Hide comments and newlines from debug output ([#404](https://github.com/motdotla/dotenv/pull/404)) + +## [13.0.0](https://github.com/motdotla/dotenv/compare/v12.0.4...v13.0.0) (2022-01-16) + +### Added + +* _Breaking:_ Add type file for `config.js` ([#539](https://github.com/motdotla/dotenv/pull/539)) + +## [12.0.4](https://github.com/motdotla/dotenv/compare/v12.0.3...v12.0.4) (2022-01-16) + +### Changed + +* README updates +* Minor order adjustment to package json format + +## [12.0.3](https://github.com/motdotla/dotenv/compare/v12.0.2...v12.0.3) (2022-01-15) + +### Changed + +* Simplified jsdoc for consistency across editors + +## [12.0.2](https://github.com/motdotla/dotenv/compare/v12.0.1...v12.0.2) (2022-01-15) + +### Changed + +* Improve embedded jsdoc type documentation + +## [12.0.1](https://github.com/motdotla/dotenv/compare/v12.0.0...v12.0.1) (2022-01-15) + +### Changed + +* README updates and clarifications + +## [12.0.0](https://github.com/motdotla/dotenv/compare/v11.0.0...v12.0.0) (2022-01-15) + +### Removed + +- _Breaking:_ drop support for Flow static type checker ([#584](https://github.com/motdotla/dotenv/pull/584)) + +### Changed + +- Move types/index.d.ts to lib/main.d.ts ([#585](https://github.com/motdotla/dotenv/pull/585)) +- Typescript cleanup ([#587](https://github.com/motdotla/dotenv/pull/587)) +- Explicit typescript inclusion in package.json ([#566](https://github.com/motdotla/dotenv/pull/566)) + +## [11.0.0](https://github.com/motdotla/dotenv/compare/v10.0.0...v11.0.0) (2022-01-11) + +### Changed + +- _Breaking:_ drop support for Node v10 ([#558](https://github.com/motdotla/dotenv/pull/558)) +- Patch debug option ([#550](https://github.com/motdotla/dotenv/pull/550)) + +## [10.0.0](https://github.com/motdotla/dotenv/compare/v9.0.2...v10.0.0) (2021-05-20) + +### Added + +- Add generic support to parse function +- Allow for import "dotenv/config.js" +- Add support to resolve home directory in path via ~ + +## [9.0.2](https://github.com/motdotla/dotenv/compare/v9.0.1...v9.0.2) (2021-05-10) + +### Changed + +- Support windows newlines with debug mode + +## [9.0.1](https://github.com/motdotla/dotenv/compare/v9.0.0...v9.0.1) (2021-05-08) + +### Changed + +- Updates to README + +## [9.0.0](https://github.com/motdotla/dotenv/compare/v8.6.0...v9.0.0) (2021-05-05) + +### Changed + +- _Breaking:_ drop support for Node v8 + +## [8.6.0](https://github.com/motdotla/dotenv/compare/v8.5.1...v8.6.0) (2021-05-05) + +### Added + +- define package.json in exports + +## [8.5.1](https://github.com/motdotla/dotenv/compare/v8.5.0...v8.5.1) (2021-05-05) + +### Changed + +- updated dev dependencies via npm audit + +## [8.5.0](https://github.com/motdotla/dotenv/compare/v8.4.0...v8.5.0) (2021-05-05) + +### Added + +- allow for `import "dotenv/config"` + +## [8.4.0](https://github.com/motdotla/dotenv/compare/v8.3.0...v8.4.0) (2021-05-05) + +### Changed + +- point to exact types file to work with VS Code + +## [8.3.0](https://github.com/motdotla/dotenv/compare/v8.2.0...v8.3.0) (2021-05-05) + +### Changed + +- _Breaking:_ drop support for Node v8 (mistake to be released as minor bump. later bumped to 9.0.0. see above.) + +## [8.2.0](https://github.com/motdotla/dotenv/compare/v8.1.0...v8.2.0) (2019-10-16) + +### Added + +- TypeScript types + +## [8.1.0](https://github.com/motdotla/dotenv/compare/v8.0.0...v8.1.0) (2019-08-18) + +### Changed + +- _Breaking:_ drop support for Node v6 ([#392](https://github.com/motdotla/dotenv/issues/392)) + +# [8.0.0](https://github.com/motdotla/dotenv/compare/v7.0.0...v8.0.0) (2019-05-02) + +### Changed + +- _Breaking:_ drop support for Node v6 ([#302](https://github.com/motdotla/dotenv/issues/392)) + +## [7.0.0] - 2019-03-12 + +### Fixed + +- Fix removing unbalanced quotes ([#376](https://github.com/motdotla/dotenv/pull/376)) + +### Removed + +- Removed `load` alias for `config` for consistency throughout code and documentation. + +## [6.2.0] - 2018-12-03 + +### Added + +- Support preload configuration via environment variables ([#351](https://github.com/motdotla/dotenv/issues/351)) + +## [6.1.0] - 2018-10-08 + +### Added + +- `debug` option for `config` and `parse` methods will turn on logging + +## [6.0.0] - 2018-06-02 + +### Changed + +- _Breaking:_ drop support for Node v4 ([#304](https://github.com/motdotla/dotenv/pull/304)) + +## [5.0.0] - 2018-01-29 + +### Added + +- Testing against Node v8 and v9 +- Documentation on trim behavior of values +- Documentation on how to use with `import` + +### Changed + +- _Breaking_: default `path` is now `path.resolve(process.cwd(), '.env')` +- _Breaking_: does not write over keys already in `process.env` if the key has a falsy value +- using `const` and `let` instead of `var` + +### Removed + +- Testing against Node v7 + +## [4.0.0] - 2016-12-23 + +### Changed + +- Return Object with parsed content or error instead of false ([#165](https://github.com/motdotla/dotenv/pull/165)). + +### Removed + +- `verbose` option removed in favor of returning result. + +## [3.0.0] - 2016-12-20 + +### Added + +- `verbose` option will log any error messages. Off by default. +- parses email addresses correctly +- allow importing config method directly in ES6 + +### Changed + +- Suppress error messages by default ([#154](https://github.com/motdotla/dotenv/pull/154)) +- Ignoring more files for NPM to make package download smaller + +### Fixed + +- False positive test due to case-sensitive variable ([#124](https://github.com/motdotla/dotenv/pull/124)) + +### Removed + +- `silent` option removed in favor of `verbose` + +## [2.0.0] - 2016-01-20 + +### Added + +- CHANGELOG to ["make it easier for users and contributors to see precisely what notable changes have been made between each release"](http://keepachangelog.com/). Linked to from README +- LICENSE to be more explicit about what was defined in `package.json`. Linked to from README +- Testing nodejs v4 on travis-ci +- added examples of how to use dotenv in different ways +- return parsed object on success rather than boolean true + +### Changed + +- README has shorter description not referencing ruby gem since we don't have or want feature parity + +### Removed + +- Variable expansion and escaping so environment variables are encouraged to be fully orthogonal + +## [1.2.0] - 2015-06-20 + +### Added + +- Preload hook to require dotenv without including it in your code + +### Changed + +- clarified license to be "BSD-2-Clause" in `package.json` + +### Fixed + +- retain spaces in string vars + +## [1.1.0] - 2015-03-31 + +### Added + +- Silent option to silence `console.log` when `.env` missing + +## [1.0.0] - 2015-03-13 + +### Removed + +- support for multiple `.env` files. should always use one `.env` file for the current environment + +[7.0.0]: https://github.com/motdotla/dotenv/compare/v6.2.0...v7.0.0 +[6.2.0]: https://github.com/motdotla/dotenv/compare/v6.1.0...v6.2.0 +[6.1.0]: https://github.com/motdotla/dotenv/compare/v6.0.0...v6.1.0 +[6.0.0]: https://github.com/motdotla/dotenv/compare/v5.0.0...v6.0.0 +[5.0.0]: https://github.com/motdotla/dotenv/compare/v4.0.0...v5.0.0 +[4.0.0]: https://github.com/motdotla/dotenv/compare/v3.0.0...v4.0.0 +[3.0.0]: https://github.com/motdotla/dotenv/compare/v2.0.0...v3.0.0 +[2.0.0]: https://github.com/motdotla/dotenv/compare/v1.2.0...v2.0.0 +[1.2.0]: https://github.com/motdotla/dotenv/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/motdotla/dotenv/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/motdotla/dotenv/compare/v0.4.0...v1.0.0 diff --git a/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/LICENSE b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/LICENSE new file mode 100644 index 0000000..c430ad8 --- /dev/null +++ b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Scott Motte +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/README-es.md b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/README-es.md new file mode 100644 index 0000000..978a73b --- /dev/null +++ b/node_modules/.pnpm/dotenv@17.2.2/node_modules/dotenv/README-es.md @@ -0,0 +1,405 @@ +
+🎉 announcing dotenvx. run anywhere, multi-environment, encrypted envs. +
+ +  + +
+ +**Special thanks to [our sponsors](https://github.com/sponsors/motdotla)** + + +
+ Tuple +
+ Tuple, the premier screen sharing app for developers on macOS and Windows. +
+
+
+ +# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv) + +dotenv + +Dotenv es un módulo de dependencia cero que carga las variables de entorno desde un archivo `.env` en [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). El almacenamiento de la configuración del entorno separado del código está basado en la metodología [The Twelve-Factor App](http://12factor.net/config). + +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard) +[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE) + +## Instalación + +```bash +# instalación local (recomendado) +npm install dotenv --save +``` + +O installación con yarn? `yarn add dotenv` + +## Uso + +Cree un archivo `.env` en la raíz de su proyecto: + +```dosini +S3_BUCKET="YOURS3BUCKET" +SECRET_KEY="YOURSECRETKEYGOESHERE" +``` + +Tan prónto como sea posible en su aplicación, importe y configure dotenv: + +```javascript +require('dotenv').config() +console.log(process.env) // elimine esto después que haya confirmado que esta funcionando +``` + +.. o usa ES6? + +```javascript +import * as dotenv from 'dotenv' // vea en https://github.com/motdotla/dotenv#como-uso-dotenv-con-import +// REVISAR LINK DE REFERENCIA DE IMPORTACIÓN +dotenv.config() +import express from 'express' +``` + +Eso es todo. `process.env` ahora tiene las claves y los valores que definiste en tu archivo `.env`: + +```javascript +require('dotenv').config() + +... + +s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {}) +``` + +### Valores multilínea + +Si necesita variables de varias líneas, por ejemplo, claves privadas, ahora se admiten en la versión (`>= v15.0.0`) con saltos de línea: + +```dosini +PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- +... +Kh9NV... +... +-----END RSA PRIVATE KEY-----" +``` + +Alternativamente, puede usar comillas dobles y usar el carácter `\n`: + +```dosini +PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n" +``` + +### Comentarios + +Los comentarios pueden ser agregados en tu archivo o en la misma línea: + +```dosini +# This is a comment +SECRET_KEY=YOURSECRETKEYGOESHERE # comment +SECRET_HASH="something-with-a-#-hash" +``` + +Los comentarios comienzan donde existe un `#`, entonces, si su valor contiene un `#`, enciérrelo entre comillas. Este es un cambio importante desde la versión `>= v15.0.0` en adelante. + +### Análisis + +El motor que analiza el contenido de su archivo que contiene variables de entorno está disponible para su uso. Este Acepta una Cadena o un Búfer y devolverá un Objeto con las claves y los valores analizados. + +```javascript +const dotenv = require('dotenv') +const buf = Buffer.from('BASICO=basico') +const config = dotenv.parse(buf) // devolverá un objeto +console.log(typeof config, config) // objeto { BASICO : 'basico' } +``` + +### Precarga + +Puede usar el `--require` (`-r`) [opción de línea de comando](https://nodejs.org/api/cli.html#-r---require-module) para precargar dotenv. Al hacer esto, no necesita requerir ni cargar dotnev en el código de su aplicación. + +```bash +$ node -r dotenv/config tu_script.js +``` + +Las opciones de configuración a continuación se admiten como argumentos de línea de comandos en el formato `dotenv_config_